Building a Super Basic WordPress Plugin

The true power in using a content management system like WordPress lies in the ability to create custom plugins to extend the platform.

Create a Plugin

To create a plugin, choose a name for your plugin and create a folder with that name in the directory wp-content/plugins. Don’t include spaces in the name of the plugin when creating the folder — use hyphens instead.

Inside of the folder, there must be a PHP file with the same name as the plugin.

For example, to create a plugin called cats-in-pajamas, navigate to the WordPress root directory and create the necessary structure:

mkdir wp-content/plugins/cats-in-pajamas
cd wp-content/plugins/cats-in-pajamas
touch cats-in-pajamas.php

In the newly created file (cats-in-pajamas.php), add the following information:

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
  /**
   * Plugin Name: Cats in Pajamas
   * Plugin URI: http://cats-in-pajamas.io
   * Description: This plugin posts pictures of cats in pajamas at
   *   regular intervals.
   * Author: tecz
   * Version: 0.1.0
   * Author URI: http://teczd.com
   * License: GPLv2 or later
   */
 ?>
 

Though the plugin doesn’t yet do anything, it should be visible on the site’s Plugins page.

Make the Plugin Do Something

Now, the plugin needs to actually do something.

Let’s start by adding a picture of a cat in the footer. Open the cats-in-pajamas.php file again, and add the following after the comment (but before the closing ?> tag)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 <?php
  /**
   * Plugin Name: Cats in Pajamas
   * Plugin URI: http://cats-in-pajamas.io
   * Description: This plugin posts pictures of cats in pajamas at
   *   regular intervals.
   * Author: tecz
   * Version: 0.1.0
   * Author URI: http://teczd.com
   * License: GPLv2 or later
   */

  function cats_in_pajamas_footer() {
    <div style="width: 150px; text-align: center;">
      <img src="http://teczd.com/assets/pajama-cat.jpg" alt="Pajama Cat!" />
    </div>  
  }
  
  add_action( 'wp-footer', 'cats_in_pajamas_plugin_footer' );
  
?>

Now, navigate to the Plugins section of the site and activate the Cats in Pajamas plugin. Navigate back to the site’s home page, and a new friend should appear in the footer:

Pajama Cat!

Make it Do Whatever You Want

Now that the basic structure for a plugin is in place, you can make it do whatever you want it to do. The plugin that was built in this example is extremely basic, to gain a better understanding of everything that can be done through plugins view the Plugin API page of the Wordpress Codex.

View the Source

View source on GitHub


This is, of course, an overly simplistic demonstration of how to setup a basic plugin for Wordpress.

For more information about setting up Wordpress plugins, see the following resources.

More Reading: