WordPress Plugin Development

    Tim Smith
    Share

    If you’ve ever used WordPress to build a site quickly, chances are you’ve used one of the many plugins that are offered to extend the functionality of this popular blogging software. Plugins are one of the many things that make WordPress so attractive. If you need an image gallery or a contact form, there’s probably a plugin already available that you can download and use. There are times, however, when you can’t quite find what you need from existing plugins. This article will show you how to create your own WordPress plugins by walking you through an example to display some text using a widget in a the sidebar.

    The Main Plugin File

    Plugins are detected automatically from the wp-content/plugins directory within your WordPress installation directory. When creating a new plugin, you should create a new subdirectory there. The name of the subdirectory can be anything you want; a sensible option would be to call it the name of your plugin. Try to avoid generic names such as “textwidget” or “shoppingcart” as this may have already been used with another plugin and will cause problems should you wish to distribute it to other users of WordPress. For this example, create a subdirectory named phpmaster_examplewidget.

    WordPress detects that a plugin is available from a descriptor placed in the comments of a PHP file. The descriptor must provide the basic information about what the plugin does, who created it, and its license information. This is what WordPress uses to identify that a plugin is present and ready to be activated. This example plugin will contain the definition at the top a file placed in your newly created phpmaster_examplewidget directory. The name of the file is also arbitrary but it’s advisable to provide a meaning name. This example will call the file widget_init.php.

    <?php
    /* 
    Plugin Name: Simple Text Plugin
    Plugin URI: http://www.example.com/textwidget
    Description: An example plugin to demonstrate the basics of putting together a plugin in WordPress
    Version: 0.1 
    Author: Tim Smith 
    Author URI: http://www.example.com
    License: GPL2 
    
        Copyright 2011  Tim Smith
    
        This program is free software; you can redistribute it and/or
        modify it under the terms of the GNU General Public License,
        version 2, as published by the Free Software Foundation. 
    
        This program is distributed in the hope that it will be useful,
        but WITHOUT ANY WARRANTY; without even the implied warranty of 
        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
        GNU General Public License for more details. 
    
        You should have received a copy of the GNU General Public License 
        along with this program; if not, write to the Free Software 
        Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 
        02110-1301  USA 
    */

    This is the required structure for any plugin you’ll create for WordPress. Now when you log in and look at the plugin administration screen in WordPress you’ll see the new plugin is ready for activation.

    WordPress plugin is registered

    You can see all of the information you entered in the comments section describing the plugin is displayed here. You can activate it now if you wish, but you still need to add some functionality before it does anything.

    The file that has this definition is now considered to be the starting point for any code associated with the plugin. The code that appears after the definition comments will be executed giving you the opportunity to initialize the plugin and its features.

    WordPress Widgets

    WordPress provides a class which you can extend named WP_Widget. When you extend it, your own widget will be available to any sidebar that your theme offers. WordPress ships with a number of default widgets such as “Recent Posts” and “Archives” which extend WP_Widget.

    The WP_Widget class provides four methods which should be overridden:

    • __construct() – call the parent constructor and initialize any class variables
    • form() – display a form for the widget in the admin view to customize the widget’s properties
    • update() – update the widget’s properties specified in the form in the admin view
    • widget() – display the widget on the blog

    The Constructor

    The constructor is like any other constructor you’ve probably written. The important thing to remember here is to call the parent constructor which can take three arguments: an identifier for the widget, the friendly name of the widget (this will appear as the title of the widget in the admin widget screen), and an array detailing the properties of the widget (which only needs a “description” value).

    <?php
    class TextWidget extends WP_Widget
    {
        public function __construct() {
            parent::__construct("text_widget", "Simple Text Widget",
                array("description" => "A simple widget to show how WP Plugins work"));
        }
    }

    With the basic widget structure in place, you’ll want to register the widget and make sure this is done at a time when all the other widgets are being initialized. Registering a widget is done through the register_widget() function which takes a single argument, the name of the class which extends WP_Widget. This call to register the widget must be called at an appropriate time, so the particular WordPress hook you’ll want to use is called “widgets_init”. To associate registering the widget with the hook, you use add_action() which takes the name of the hook as the first argument and a function to execute as the second. (The second argument can either be the string name of a function or closure.) This code should go directly under the descriptor of the plugin that was created in widget_init.php.

    <?php
    add_action("widgets_init",
        function () { register_widget("TextWidget"); });
    ?>

    Now that it has been registered and initialized, you’ll be able to see your widget available for use.

    The form() method

    The example widget here should let you enter a title and some text to be displayed when viewed on the blog, so in order to be able to amend these two aspects of the widget you need to create a form to prompt for these values. The form() method is used in the widget administration screen to display fields which you can later use to alter the functionality of the widget on the site itself. The method takes one argument, an $instance array of variables associated with the widget. When the form is submitted, the widget will call the update() method which allows you to update the fields in $instance with new values. Later, widget() will be called and will make use of $instance to display the values.

    <?php
    public function form($instance) {
        $title = "";
        $text = "";
        // if instance is defined, populate the fields
        if (!empty($instance)) {
            $title = $instance["title"];
            $text = $instance["text"];
        }
    
        $tableId = $this->get_field_id("title");
        $tableName = $this->get_field_name("title");
        echo '<label for="' . $tableId . '">Title</label><br>';
        echo '<input id="' . $tableId . '" type="text" name="' .
            $tableName . '" value="' . $title . '"><br>';
    
        $textId = $this->get_field_id("text");
        $textName = $this->get_field_name("text");
        echo '<label for="' . $textId . '">Text</label><br>';
        echo '<textarea id="' . $textId . '" name="' . $textName .
            '">' . $text . '</textarea>';
    }

    You use WP_Widget‘s get_field_id() method and get_field_name() method to create IDs and names for the form fields respectively. WordPress will generate unique identifiers for you so as not to clash with other widgets in use, and when the form is submitted the values will update the relevant $instance array items. You can use the passed $instance argument to populate the form fields with values should they already be set.

    This is what the form looks like in the admin view:

    The example plugin's admin

    The parent <form> element itself, the Save button, and the Delete and Close links are generated for you automatically by WordPress so there is no need to explicitly code them. The form will post the variables and call the update() method so the new values can be inserted into $instance.

    The update() Method

    update() gives you an opportunity to validate and sanitize the instance variables before they are used by the widget. Here you can make decisions based on the old values and update the new values accordingly. update() must return an array which contains the items you expect to use when displaying the widget. WordPress passes two arguments to it, an array with the new instance values from the form, and an array with the original instance values.

    <?php
    public function update($newInstance, $oldInstance) {
        $values = array();
        $values["title"] = htmlentities($newInstance["title"]);
        $values["text"] = htmlentities($newInstance["text"]);
        return $values;
    }

    WordPress will persist these values for you so there is no need to implement that functionality.

    The widget() Method

    The widget() method is used to display content within the widget when it appears in the sidebar on your blog. Output from the method will render the blog page. WordPress passes the widget() method two arguments: the first is $args which is an array detailing information about the widget, and the second is the $instance which you can use to get the output the data associated with the widget. $args really won’t affect this example so I won’t go into it; just remember $instance is the second argument.

    <?php
    public function widget($args, $instance) {
        $title = $instance["title"];
        $text = $instance["text"];
    
        echo "<h2>$title</h2>";
        echo "<p>$text</p>";
    }

    This will produce the following possible output on the site:

    the example plugin displayed

    And that’s it! Putting all this together will give you a very simple widget to display text on the blog side of a WordPress installation.

    Summary

    You’re now familiar with the necessary groundwork for a WordPress plugin that ensures WordPress can detect and activate it, and extending the WP_Widget class to create your own widgets. The example widget presented in this article demonstrated the ability customize the widget’s display through an admin-provided configuration form. Though simple, it highlighted the basic WP_Widget methods you’ll use and you’ll easily be able to move on from this example and create greater functionality for your own WordPress driven sites. The code for this example is available under PHPMaster’s GitHub account so you can have a look at the code in it’s entirety.

    Image via bioraven / Shutterstock