WordPress Plugin Development

Share this article

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

Frequently Asked Questions about WordPress Plugin Development

How do I start developing a WordPress plugin?

To start developing a WordPress plugin, you need to have a basic understanding of PHP, HTML, CSS, and JavaScript. Once you have these skills, you can start by creating a new folder in your WordPress plugins directory. Name this folder after your plugin. Inside this folder, create a PHP file with the same name. This file will serve as the main file for your plugin. In this file, you will need to include a header comment which tells WordPress that a plugin exists here. After setting up the basic structure, you can start writing the functionality of your plugin.

What are the best practices for WordPress plugin development?

Some of the best practices for WordPress plugin development include: using proper naming conventions to avoid function name conflicts with other plugins, using WordPress hooks and filters where possible, ensuring your plugin is secure by validating and sanitizing user input, and making your plugin translatable to reach a wider audience. It’s also important to keep your code clean and well-commented for future reference and updates.

How can I make my WordPress plugin compatible with all themes?

Ensuring your WordPress plugin is compatible with all themes can be challenging due to the vast number of themes available. However, adhering to WordPress coding standards, using hooks and filters instead of modifying core files, and testing your plugin with different themes can help ensure compatibility. It’s also recommended to provide clear documentation and support for your plugin users.

How do I debug my WordPress plugin?

Debugging your WordPress plugin involves identifying and fixing any issues or errors that may arise during its development. WordPress comes with a built-in debugging system that you can enable in your wp-config.php file. By setting WP_DEBUG to true, you can display PHP errors on the front end of your website. Additionally, using a PHP IDE with a debugger can help you step through your code and find issues more efficiently.

How can I ensure the security of my WordPress plugin?

Ensuring the security of your WordPress plugin involves several steps. First, always validate and sanitize user input to prevent SQL injection attacks. Second, use nonces to verify the source of requests. Third, use proper file permissions in your plugin files. Fourth, use the WordPress API functions for data manipulation instead of custom SQL queries. Lastly, regularly update and test your plugin for any potential security vulnerabilities.

How do I make my WordPress plugin SEO-friendly?

Making your WordPress plugin SEO-friendly involves ensuring that it doesn’t negatively impact the website’s loading speed, as this is a key factor in SEO. Also, if your plugin adds content to the website, make sure it’s easily crawlable and indexable by search engines. If your plugin involves images, make sure to add alt tags. Lastly, ensure your plugin is compatible with popular SEO plugins.

How do I update my WordPress plugin?

Updating your WordPress plugin involves making the necessary changes to your plugin files and then incrementing the version number in your plugin’s header comment. Once you’ve tested the updated version and ensured it works correctly, you can upload it to the WordPress plugin repository. If your plugin is hosted on the WordPress plugin repository, users will be notified of the update in their WordPress dashboard.

How can I make my WordPress plugin user-friendly?

Making your WordPress plugin user-friendly involves providing clear and detailed documentation, including screenshots or videos where necessary. Also, ensure your plugin’s settings and options are intuitive and easy to understand. Providing prompt and helpful support can also greatly enhance user experience.

How do I test my WordPress plugin?

Testing your WordPress plugin involves checking its functionality in different scenarios and with different themes and plugins. You can use automated testing tools like PHPUnit for unit testing. Also, consider using debugging tools to identify any errors or issues. It’s also a good idea to have beta testers who can provide feedback before you release your plugin.

How can I monetize my WordPress plugin?

There are several ways to monetize your WordPress plugin. You can offer a free version with basic features and a premium version with advanced features. You can also offer paid add-ons for your free plugin. Another option is to offer your plugin for free and provide paid support or custom development services.

Tim SmithTim Smith
View Author

Tim Smith is a freelance web designer and developer based in Harrogate, North Yorkshire in the UK. He started out programming the Spectrum 48k and has never looked back. When he's not boring his other half with the details of his latest project, Tim can be found with his beloved Korgs making music, reading a good book or in the pub.

Intermediate
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week