trace( "maybe this will work…" );

WordPress Plugin Quickstart Tutorial

WordPress Plugin Icon

Problem: “I want to build my own WordPress plugin, but after sifting through the WordPress documentation, I don’t really know where to start.”

WordPress plugins are a fantastic way to add new functionality to your website, but approaching plugins for the first time can be daunting, even for experienced programmers. This quickstart tutorial provides a step-by-step guide to creating a WordPress plugin from scratch. It is designed for WordPress users who have never built a plugin before, but have had some experience with PHP. The goal of this tutorial is to get a simple plugin operational in a minimal amount of time. For all of the details on building a plugin, see the WordPress plugin How To.

By the end of this tutorial, you will have a basic understanding of how to extend WordPress functionality with plugins, how to set options via the WordPress database, as well as how to define an admin menu for your plugin.

Getting Started

We’re going to build a very simple plugin entitled “Hello Plugin.” This plugin will add a greeting to the title of every post in your WordPress blog. For example, “My first post” will become “Hello, My first post.” It’s trivial, but it gives us a comfortable starting point for our first foray into the potentially complicated world of WordPress plugins.

Step 1: Create the plugin directory

Open the folder of your WordPress installation. You should generally develop plugins on a local installation of WordPress, but if you don’t have that set up, it’s ok to follow along on your live WordPress site. If this is the case, you’ll have to log in to your WordPress server via ftp. Navigate to the following folder.

wordpress_installation/wp-content/plugins

Create a folder with the same name as the plugin. In this case, you should create a folder called “helloPlugin”.

WordPress plugin folder

Step 2: Create the main PHP file in the plugin’s folder

It needs to have a unique name, so you’ll generally want to create a file with the same name as your plugin. In this case, we’ll create a file called “helloPlugin.php”.

WordPress plugin main PHP file

Step 3: Make the plugin visible to WordPress

This is accomplished by putting an “information header” at the top of the main PHP file. Add this to “helloPlugin.php”

<?php
/*
Plugin Name: Hello Plugin
Plugin URI: http://www.slekx.com
Description: My first plugin
Version: 1.0
Author: Ryan Hodson
Author URI: http://www.slekx.com
*/

?>

All this does is define some meta data for the plugin. Change the values to match your situation. Now, when you go to the admin menu and click on Plugins>Installed, “Hello Plugin” should appear on the list of installed plugins.

You CANNOT skip this step. If you do, WordPress will not find your plugin, and it won’t show up on the admin page.

Step 4: Define the plugin’s custom behavior

The easiest way to add new behaviors is by using the built-in WordPress plugin “hooks.” These hooks tell WordPress to call a PHP function at a specified point in the WordPress page rendering process. We’ll define our behavior by adding the following code to “helloPlugin.php”:

add_filter('the_title', 'helloPlugin_title');

function helloPlugin_title($content){
    return 'Hello, ' . $content;
}

The ‘add_filter()’ line tells WordPress to add the function ‘helloPlugin_title();’ to a filter hook called ‘the_title’.
Now, whenever WordPress encounter’s a post’s title, it will run it through ‘helloPlugin_title();’ before it is displayed. This function prepends the string “Hello, ” to the parameter passed to it.

The argument(s) passed to the hooked function vary depending on which hook it is attached to. For example, the ‘get_pages’ hook passes an array of pages to the target function, while ‘the_title’ simply passes the title of the post as a string. Filter functions should always return the processed data. For the complete list of available filter hooks, see the WordPress Filter Reference

Now, try activating the plugin and viewing a page. All of your post and page titles should be prepended with “Hello, “.

This example only demonstrates the use of a “filter” hook. “Action” hooks are also available. “Filters” typically perform operations on the content before it is displayed, while action hooks are triggered by specific events in the WordPress rendering process (for example, initializing an admin page). To read more about filter and action hooks, visit the WordPress Plugin API documentation.

Step 5: Add options for the user to set

Instead of having a hardcoded “Hello, ” as a greeting, we should let the user define what greeting they want to display. Since the option is a relatively static value, we can save it using the WordPress “options” mechanism. If we were doing something that needed to record lots of data in the database, we would want to create our own table for the plugin. Add an option by adding the following code to “helloPlugin.php”, immediately after the information header:

add_option("helloPlugin_greeting", "Hello, ");

This tells WordPress to add an option called “helloPlugin_greeting” to its options table and give it an initial value of “Hello, “. We prepended the option name with the plugin’s title to prevent naming conflicts with other plugins.

We can reference this option by using calling:

get_option("helloPlugin_greeting");

We’ll use this to tell the ‘helloPlugin_title();’ function what greeting to use. Change ‘helloPlugin_title();’ to the following:

function helloPlugin_title($content){
    $greeting = get_option("helloPlugin_greeting");
    return "$greeting " . $content;
}

When you load a page it should still display “Hello, ” before all of the post titles.

Step 6: Add an administrative menu for the plugin

Generally, you will want users to be able to edit option values in the admin interface so they don’t have to deal with editing PHP code. Fortunately, WordPress makes this a relatively easy process:

  1. Create a menu item for your plugin
  2. Define the html for the options page for your plugin (step 7)

First, we need to add the plugin to an existing admin menu. We’ll put it under the “Settings” menu. It is also possible (but discouraged by WordPress) to add new top level menus. See Adding Administrative Menus for details. To display a plugin in an admin menu, you need two functions. First, you need to add a function to the action hook “admin_menu”. Add this to the main PHP file.

add_action('admin_menu', 'helloPlugin_menu');

This tells WordPress to call the ‘helloPlugin_menu();’ function every time WordPress renders the admin menu. Now we need to define that function:

function helloPlugin_menu(){
    add_submenu_page('options-general.php', 'Edit Hello Plugin', 'Hello Plugin', 'administrator', 'hello-plugin-edit', 'helloPlugin_options');
}

This function uses the built-in function ‘add_submenu_page();’ to add our plugin to the admin menu. ‘add_submenu_page();’ has the following signature:

add_submenu_page(parent, page_title, menu_title, capability, handle, [function]);
  • parent – The parent menu. For built-in menus, this is the file that supplies the top level menu, for custom top level menus, this is the parent’s handle. The following define some of the common top level menu files:
    • For Settings: add_submenu_page(‘options-general.php’,…)
    • For Write: add_submenu_page(‘post-new.php’,…)
    • For Manage: add_submenu_page(‘edit.php’,…)
    • For Design: add_submenu_page(‘themes.php’,…)
    • For Comments: add_submenu_page(‘edit-comments.php’,…)
    • For Plugins: add_submenu_page(‘plugins.php’,…)
    • For Users: add_submenu_page(‘users.php’,…)
  • page_title – The title of the page when the menu item is selected.
  • menu_title – The text displayed in the menu.
  • capability – The necessary authorization to use this plugin. This can be “administrator”, “editor”, “author”, “contributor”, “subscriber”. For detailed descriptions of these roles, see Summary of Roles.
  • handle – The url of the admin page. This must be unique.
  • function – The function that displays the html of the admin page.

We have yet to define the function that displays the admin page, which we called “helloPlugin_options();” in the above function. We’ll define it as follows:

function helloPlugin_options(){
    echo "Hello Plugin options will go here...";
}

Try reloading your admin interface. Under the “Settings” menu, “Hello Plugin” should show up. When you click it, the admin page should read “Hello Plugin options will go here…” Now we’re ready to create the html that will allow the options to be changed via the admin page.

Step 7: Define the html for the options page in the admin interface

This section is a summary of Creating Options Pages. We’ll use the new settings API to create an html form that updates the “helloPlugin_greeting” option that we defined in step 5. First, register the options that are going to be changed by adding this to ‘helloPlugin_menu();’

add_action('admin_init', 'register_options');

This is another action hook that tells WordPress to call ‘register_options();’ when it encounters the ‘admin_init’ event. Now, we need to define ‘register_options();’

function register_options(){
    register_setting('hello-plugin-settings', 'helloPlugin_greeting');
}

This tells WordPress that we will change the ‘helloPlugin_greeting’ option in the upcoming admin page. If you wanted to add another option, you would do so as follows:

function register_options(){
    register_setting('hello-plugin-settings', 'helloPlugin_greeting');
    register_setting('hello-plugin-settings', 'helloPlugin_anotherOption');
}

Now that our options are registered, we are ready to define the html to display in the admin page. Change ‘helloPlugin_options();’ to this:

function helloPlugin_options(){
?>
<div class="wrap">
<h2>Hello Plugin Options</h2>
<form method='POST' action='options.php'>
    <?php settings_fields('hello-plugin-settings'); ?>
    <table class='form-table'>
        <tr valign='top'>
        <th scope='row'>Greeting</th>
        <td><input type='text' name='helloPlugin_greeting' value='<?php echo get_option('helloPlugin_greeting'); ?>' /></td>
        </tr>
        <!-- if you had more options, you would create another row, similar to the one above -->
    </table>
    <p class='submit'>
        <input type='submit' class='button-primary' value='<?php _e('Save Changes') ?>' />
    </p>
</form>
</div>
<?php }

Here, we define a form that updates the ‘helloPlugin_greeting’ option. This is primarily accomplished by the line

<?php settings_fields('hello-plugin-settings'); ?>

This takes care of the backend processes necessary to save the option(s). Make sure that the line

<input type='text' name='helloPlugin_greeting' value='<?php echo get_option('helloPlugin_greeting'); ?>' />

matches the name of the option that you are changing. Everything is contained in “div class=’wrap’” tag because this is the standard admin page divider class.

We’re Done!

We’re finally ready to test our finished plugin. Try changing the value of ‘Greeting’ via the admin page. When you reload a post, the title should reflect your new greeting.

For reference, here’s all of the code together:

<?php
/*
Plugin Name: Hello Plugin
Plugin URI: http://www.slekx.com
Description: My first plugin
Version: 1.0
Author: Ryan Hodson
Author URI: http://www.slekx.com
*/


add_option("helloPlugin_greeting", "Hello, ");

add_filter('the_title', 'helloPlugin_title');

function helloPlugin_title($content){
    $greeting = get_option("helloPlugin_greeting");
    return "$greeting " . $content;
}

add_action('admin_menu', 'helloPlugin_menu');

function helloPlugin_menu(){
    add_submenu_page('options-general.php', 'Edit Hello Plugin', 'Hello Plugin', 'administrator', 'hello-plugin-edit', 'helloPlugin_options');
    add_action('admin_init', 'register_options');
}

function register_options(){
    register_setting('hello-plugin-settings', 'helloPlugin_greeting');
}

function helloPlugin_options(){
?>
<div class="wrap">
<h2>Hello Plugin Options</h2>
<form method='POST' action='options.php'>
    <?php settings_fields('hello-plugin-settings'); ?>
    <table class='form-table'>
       
        <tr valign='top'>
        <th scope='row'>Greeting</th>
        <td><input type='text' name='helloPlugin_greeting' value='<?php echo get_option('helloPlugin_greeting'); ?>' /></td>
        </tr>
       
    </table>
    <p class='submit'>
        <input type='submit' class='button-primary' value='<?php _e('Save Changes') ?>' />
    </p>
</form>
</div>
<?php }

?>

That’s all there is to creating a WordPress plugin from scratch. “Hello Plugin” isn’t all that useful, but it is a full-fledged plugin, complete with a configurable option and its own admin page. We skipped over a few of the details in writing WordPress plugins, but links to those details can be found throughout this walkthrough. Hopefully, this tutorial has set you on your way to creating a groundbreaking plugin of your own. If you would like some free advertising for your new plugin, feel free to post it in a comment below.


January 6th, 2010 at 8:14 pm

Posted in WordPress

8 Responses to 'WordPress Plugin Quickstart Tutorial'

Subscribe to comments with RSS or TrackBack to 'WordPress Plugin Quickstart Tutorial'.

  1. Not so bad tutorial. Thank you for this.

    Dario

    23 Feb 10 at 11:56 am

  2. Thanks :-)

    Ryan

    1 Mar 10 at 1:05 pm

  3. great tutorial! it works perfect!

    ripley

    5 Oct 10 at 7:14 am

  4. Skip Hop Studio Diaper Tote Handbag is awesome.So a lot of pockets – and not these small, worthless pockets, either. Almost all of the actual pockets are a wonderful size and really support maintain every thing organized. The handles are a great length and fit nicely over the actual shoulder; the handle shoulder straps also remain put on my own arm, which is actually vital as soon as you are having a newborn. The bag appears good, too. Not as well fancy, but not as well casual. (I’ve it in black) The material is soft (can’t consider of a far better word) so it is uncomplicated to squeeze in to tight spaces – but yet it’s sturdy. I have a Fleurville Lexi tote and I adore it, too, but that bag is actually kind of inflexible. I assume that Skip*Hop will turn into my daily tote. It is a bit huge – so if you are not in to huge totes this may be superior as an over-night diaper handbag.

    Barbara Campillo

    26 Oct 10 at 8:10 pm

  5. If you’re still on the fence: grab your favorite earphones, head down to a Best Buy and ask to plug them into a Zune then an iPod and see which one sounds better to you, and which interface makes you smile more. Then you’ll know which is right for you.

    marivkan

    19 Nov 10 at 10:08 pm

  6. and secondly,the frequency you update is too high .we are so excited of that .maybe cause that we forget to comments..:)..

    Kelli

    19 Nov 10 at 10:22 pm

  7. Just wanted to contribute a article marketing resource, not too big, not too small….

    Ulysses Davault

    25 May 11 at 7:46 pm

  8. Awesome tutorial nice sharing mate.

Leave a Reply