How to Make a Plugin for WordPress

how to make a pluginAs both a blogging platform and a site content management system (CMS), WordPress has a rich feature set and a vast array of customization options. But if you need functionality that is not built-in, you can extend the system with plugins from the Official WordPress Plugins Repository, or even write your own. All WordPress plugins are written in PHP, and can be installed through the administration panel.

This is an introduction to writing plugins, and assumes that you are familiar with administering a WordPress system, such as installation, security, and performance. You will also need to have knowledge of PHP and a thorough guide to the PHP programming language can be found at Udemy.com.

Getting Started

Sites hosted on WordPress.com have access to the most popular plugins and the system administrators do, from time to time, install more on request. However, installing plugins is blocked for security reasons. To develop and use your own plugins, you must download the free WordPress system and install it on your own hosting account or web server.

While developing plugins, you should enable WordPress’ debugging features so that you can see any errors and warnings raised by the system. To enable debugging:

  1. Open wp-config.php in the root directory of your WordPress installation.
  2. Find the line that reads: define(‘WP_DEBUG’, false);
  3. Replace that line with the code below.
    define('WP_DEBUG', true);
    define('WP_DEBUG_LOG', true);
    define('WP_DEBUG_DISPLAY', false);
    
  4. If you don’t want errors displayed in the code that is sent to web browsers, add the following directive under the last line above.
    @ini_set('display_errors', 0);

Making Your First Plugin

With WordPress configured and waiting, you are ready to create a test plugin. The code and instructions below guide you through the process of

  1. Creating a plugin that outputs a message to the debug logs;
  2. Installing the plugin in WordPress;
  3. Testing the plugin.

WordPress plugins are PHP script files, and can be created in text editors such as Notepad or Vi. Their file names must be unique among all plugins on the same WordPress system, and if you intend to distribute your plugin through the official repository, the file name should be unique among all of the plugins available there.

Start a new text file and then save it to a convenient location with a file name that is most likely to be unique. For example, “com.udemy.testplugin1.php”.

The PHP script must begin with a standard header that WordPress uses to identify the plugin and read information from. This header must include certain pieces of information in the first comments block. An example of this is shown below, taken from WordPress’s official documentation.

<?php
 /**
 * Plugin Name: Name Of The Plugin
 * Plugin URI: http://URI_Of_Page_Describing_Plugin_and_Updates
 * Description: A brief description of the Plugin.
 * Version: The Plugin's Version Number, e.g.: 1.0
 * Author: Name of the Plugin Author
 * Author URI: http://URI_Of_The_Plugin_Author
 * License: A "Slug" license name e.g. GPL2
 */
?>

The information fields can be in order, but all should be present. After the header, it is common to include any copyright and licensing information as another comments block.

From your plugin, you can add a message to the debug/error log using the error_log() function, and passing in a text string as a single argument. The string will be written to the debug.log file stored in /wp-content/ in your WordPress installation. To avoid doing this when debugging is inactive, you can check whether the WP_DEBUG variable has been set.

The code sample below demonstrates this, the plugin header, and how licensing information is included:

<?php
    /*
    Plugin Name: Udemy Test Plugin
    Plugin URI: http://www.udemy.com
    Description: Test Plugin 1 - How to Make a Plugin for WordPress
    Author: K. Von Dyson
    Version: 1.0
    Author URI: http://www.udemy.com
    License: GPL2
    */
    /*  
    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
    */
    
    if (WP_DEBUG === true) {
        error_log("Udemy Test Plugin is installed.");
    }
?>

Installing and Activating Your Plugin

The plugin shown above doesn’t do very much, but it is a valid WordPress plugin and you can install it on your system. There are two ways of doing this.

One way, is to connect to your web server (for example, using FTP) and transfer the PHP script file to the /wp-content/plugins/ directory in your WordPress installation.

The second is to “zip” the PHP script file and upload it to your system using the WordPress admin panel:

  1. Login to the administration panel /wp-admin/.
  2. From the dashboard navigation, click Plugins.
  3. Click Add New.
  4. From the tabbed items, click Upload.

Regardless of how the file is uploaded to the server, once the plugin script has been transferred to WordPress it must be activated before it will run. To do this:

  1. Login to the administration panel /wp-admin/.
  2. From the dashboard navigation, click Plugins.
  3. Find Udemy Test Plugin (or whatever you called your plugin) in the list and click Activate.

While the plugin is active, WordPress will periodically run the script and the text string will be written to debug.log. However, in order to do something actually useful and be called at the right time, the script must tell WordPress what kind of event the plugin is written to respond to.

Responding to WordPress Events

The WordPress system has an extensive collection of events, or actions, that occur at various times – such as when a page/post is requested by a browser or when new posts are added. Your plugin needs to register which actions it responds to and declare functions to be run when these events happen. When an event occurs, WordPress checks to see which active plugins are registered for that event and calls the declared function in the plugin’s PHP script.

To register a function, use the directive:

<?php add_action('hook_name', 'function_name'); ?>

It would be impractical to describe every hook action in detail as there are quite a lot of them. A comprehensive list of the hook actions supported by WordPress is available in the WordPress Plugin API documentation.

The code example below registers a function to respond to the hook the_content, which runs after the content is fetched from the database but before it is sent to the web browser. The content text is passed as an argument into the registered function – enabling this plugin to modify the content by adding a preset disclaimer to every blog post.

<?php
    /*
    Plugin Name: Udemy Test Plugin
    Plugin URI: http://www.udemy.com
    Description: Test Plugin 1 - How to Make a Plugin for WordPress
    Author: K. Von Dyson
    Version: 1.0
    Author URI: http://www.udemy.com
    License: GPL2
    */
    /*  
    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
    */
    $disclaimer = "<p>Any views or opinions presented in this article are solely those of the author and do not necessarily represent those of the company.</p>";
    add_action('the_content', 'ud_adddisclaimer');
    function ud_adddisclaimer($content) {
        global $disclaimer;
        $content = $content.$disclaimer;
        return $content;
    }
?>

Creating an Admin Page

For many plugins, it would be useful to be able to customize their operation from the WordPress admin panel, instead of having to change and re-upload the PHP script. The general process for doing this is:

1.
The admin page can be a single PHP script that displays an HTML form for collecting the options data, and posts back to itself when the submit button is pressed. An example is shown below:

<?php
if($_POST['udtest_submit'] == 'Y') {
    $disclaimer = $_POST['udtest_disclaimer'];
}
?>
<div class="wrap">
<h2>Udemy.com Test Plugin Options</h2>
<form name="udtest_form" method="post" action="<?php echo str_replace( '%7E', '~', $_SERVER['REQUEST_URI']); ?>">
<input type="hidden" name="udtest_submit" value="Y">
<h3>Disclaimer Text:</h3>
<textarea name="udtest_disclaimer" style="width: 100%;"><?php echo $disclaimer; ?></textarea>
<p class="submit">
<input type="submit" name="Submit" value="Save" />
</p>
</form>
</div>

Upload the PHP script to same directory as the main plugin file.

2.
In the main plugin script, create a new function and use the include directive to attach the admin script:

function ud_test_admin() {
    include('com.udemy.admin.php');
}

3.
Register a hook to the admin_menu action in your main plugin file. Use add_action() in the same as you did when responding to the_content events.

add_action('admin_menu', 'ud_test_admin_actions');

And then declare the responder function, for example:

function ud_test_admin_actions() {
    add_options_page('Udemy Test Plugin Admin', 'Udemy Test Plugin', 'manage_options', 'com.udemy.testplugin2.php', 'ud_test_admin');
}

In the function above, add_options_page() is used to register a new item in the WordPress administration panel’s Settings menu. add_options_page() has the declaration:

add_options_page($page_title, $menu_title, $capability, $menu_slug, $function);

Of particular note are the final three parameters.

  • $capability sets the security role needed to access the plugin’s options page.
  • $menu_slug is a text string, but must be unique among all plugins. The example function ud_test_admin_actions() uses the plugin’s file name as a menu slug.
  • $function specifies the function in the main plugin script that is to be run when the administrator clicks the link to load the plugin’s options page.

This is all you need to do to tell WordPress to create an options page for your plugin. However, the example administration page for the test plugin described so far does not actually save the values, and the example plugin script does not read them.

Finishing the Plugin

A common approach is to call the WordPress function update_option() from the administration page PHP script to store the settings in the main database. These can be retrieved by the plugin using get_option(). However, you can use whatever kind of configuration storage is most applicable to your project.

You can find additional examples of creating WordPress plugins and the available hook actions at Udemy.com. To create more useful plugins than the one described here, advanced knowledge of the PHP scripting language may be required. If you are only a beginner, the Ultimate PHP Training Bundle from Beginner to Advanced can help you expand your skills and knowledge of PHP.