WordPress Plugin Development

Tweet

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

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • http://www.psinas.com Martin Psinas

    This really would have helped me out with a contract job a few months back. Definitely going in my bookmarks. Thanks!

  • rajeev

    thank to provide good information , in WordPress plugin

  • http://mmn.ro Dana Ni

    Hello there,
    – The post title is far too general… it’s not about the development of plugins in general, it’s just about a widget creator.
    – “This is the required structure for any plugin you’ll create for WordPress.” => tells us that that (particular) text regarding the license must be there… Half wrong.
    – Nothing about the matching names of the plugin folder and plugin file? This is mandatory!
    And besides all these: Parse error: syntax error, unexpected T_FUNCTION on line 31.

    • http://oregonstate.edu Derek

      Thank you Dana for your honest candid and professional feedback. It’s great to know that there are people like you in the global community who take the time to clearly evaluate such information. I came here because of an email that intrigued me, only to find that this was no different than what one can find on the WPDEV. I think what I really desire is a graphical IDE or WP.

    • http://jusarg.com Independent Software Developer

      I agree, I was under the impression that this was more of a general plugin development tutorial not a ‘widget plugin tutorial’. Still it did help a little, so thank you.

  • http://www.wpforbusinesswebsites.com Chris Hess

    Thanks for the guide. I agree with Dana but I appreciate the guide on creating a widget.

  • http://www.nuResponse.com nuResponse

    Great tutorial. I’ve always wanted a simple starting framework for creating WP Plugins, and this helps me understand the methods I should be using and calling for Widgets.

    Keep it up!

  • http://www.weddingdresses.org.uk Paul@Wedding Dresses

    Hey Tim, This is a fantastic post, as all my sites are in wordpress its something that I’ve always wanted to do, but never got round to it, so must be fate that your post popped into my inbox.

    This definitely bookmarked, Thanks man

  • http://www.4tamil.com jeyakopy

    Thanks for the information, your description is simple methods, thanks again.. ill try to create a plugin.

  • surefoot

    This is a informative article on how to create a widget plugin.
    Regarding whether the plugin folder name and plugin file name should be same. This is not mandatory at all. I have created plugins with them different. Although only ‘Plugin File Name’ in the plugin file is mandatory. The rest is customary………

  • http://www.astralmedia.co.za Louis

    This is a project that I’ve been wanting to do for a while as I use a specific jQuery scroller ever so often in WordPress and there is no existing plugin that uses that slider. Thanks so much!

  • http://blogverize.blogspot.com Nimsrules

    This was what I was looking for. Basic tutorial for WP plugin development. Great tut!

  • http://www.nextgendigitalhome.com Craig

    Short & concise – nice introduction to WP plugin development.

  • Dave

    Really this should be titled WordPress Widget development. Other than the info header at the top of the plugin file it didn’t cover plugin development at all. It’s a bad article on WordPress plugin development, but a nice introduction to WordPress Widget development.

  • pawandeep

    add_action(“widgets_init”, function () { register_widget(“TextWidget”); });

    There is problem with add_action function in admin panel

    (Parse error: parse error, unexpected T_FUNCTION in C:wampwwwwordpresswp-contentpluginsphpmaster_examplewidgetwidget_init.php)

    Any ideas???

  • http://sdbwebsolutions.com Serg

    Great Tim! This is helping me out with one of my clients here in SJ,CA. I’d love to see more posts like this!
    Thanks for sharing:)

  • http://wpconsult.net Paul

    I don’t think you should use htmlentities when you’re saving the user input. that function is for echoing to the browser.
    If you want to sanitize user input, there are specific WordPress functions like sanitize_text_field

  • http://wpconsult.net Paul

    also, you should use esc_attr() on HTML attributes. for example when you echo the input fields

  • http://okeowoaderemi.com Okeowo Aderemi

    The Beauty of WordPress simplicity and quick to use, use to work on Joomla, had issues with documentations WordPress has Codex which is so useful if only Codex had a chm like PHP Manual and Yii it would be awesome, some of us don’t have 24hrs to internet service, very good article though.

  • http://www.themes4cms.com/ Wordpress Designer

    Ok that’s great. According to my knowledge The WordPress Maintenance are .Back Up,Checking Plugins,Updating etc..WordPress,Check Your Links,Improving Security etc..1) Backup your database and your files. You can use a number of plugins (Backup buddy is a good one) to do this, or if you trust your hosting company, there is often a file and database backup utility within your cpanel.2) Update plugins. This one is easy. Go to your plugins and look for any that need to be updated. All you need to do is click the update button and you’re done.3) Make sure you have the latest version of WordPress. WordPress will tell you on your dashboard if you need to upgrade. Simply follow the instructions – it’s not difficult.4) If you’re not using the akismet plugin, you can get it here – AKISMET . This will protect your site from spam.

  • http://www.paulund.co.uk Paul

    This is why WordPress is my favourite CMS, they make it so easy to create Widgets.

  • http://www.sharanyan.com Sharanyan

    Nowadays WP Plugin development is very complicated, because of WordPress constant update and security whole. It’s really nice tips to initilize Plugin development.

    Thanks.

  • http://www.iPhonecaptain.com mitch

    can you offer any good book suggestions to learn plugin dev and theme developpment

  • Luther Blissett

    Thumbs up for this great tutorial! – Just straight forward & simple. Thanks!

  • http://dboho.pl/ Dawid

    Thanks for the guide. I start to learn to create plug-ins. This arts is good for me.

  • Kanupriya

    Do we have to put all the code in single file?? Mine is not working. I am not getting the division of the coding modules you have given. Which one to put where?? That is really confusing me!! help !!

  • http://ChiefAlchemist.com Mark Simchock

    Helpful. I’d like to suggest that anyone who wants to dip their toes into the WordPress plugin / widget water should Google: “WordPress plugin boilerplate” as well as “WordPress widget boilerplate”. Why reinvent the wheel?

  • http://www.shubhbandh.com Shubhbandh

    I am getting following error, please help me somebody
    Parse error: syntax error, unexpected ‘public’ (T_PUBLIC) in D:xampphtdocsownpluginwp-contentpluginsphpmaster_examplewidgetwidget_init.php on line 36

  • http://sohaibshaheen.com Sohaib Shaheen

    Best tutorial regarding widgets…. I couldn’t find cleaner code over internet