This is the second part of a two part series on WordPress plugins. If you haven’t read the first part, I highly suggest reading it as it contains important basic information on plugins.
WARNING!! THIS POST IS EXTREMELY LONG. HOWEVER, IT DOES BRING A LOT OF NECESSARY AND USEFUL DATA INTO ONE PLACE.
So you’ve decided to take the next step, the plunge, into developing a WordPress plugin. Great, this will make you a lot more independent as you will no longer have to rely on others for plugins to power your site. You will be able to create the functions you want to add to your site according to your vision. I will make clear, this article will be going over the basics for creating plugins. We won’t be delving into the really deep aspects of plugin design.
What is a Plugin and Why Should I Make One?
A WordPress Plugin is a program, or a set of one or more functions, written in the PHP scripting language, that adds a specific set of features or services to the WordPress weblog, which can be seamlessly integrated with the weblog using access points and methods provided by the WordPress Plugin Application Program Interface (API).
-WordPress’s really techy definition
A WordPress plugin is there to add functions to your site which were previously lacking. It could create forums or speed up your site. If you want to add something to your site, there’s probably a way to make a plugin to do it.
“But can’t I just find the plugin and install it?” Truthfully, usually yes, but there might be instances when no one’s made the plugin you need. In this case you have two choices: hire a plugin developer or learn how to do it yourself. Hiring a plugin developer is expensive and takes time, not to mention that you and the developer may not have quite the same vision.
Learning how to develop plugins will allow you to take more control over your site and allow you to save money. Instead of paying for plugins which may not be quite what you want, you can develop something according to your vision for free.
WordPress Folder Structure
IMPORTANT!!! If you’re using multiple files you must be aware of the possibility that the plugins directory could be moved, so you’ll need to use plugin_dir_path() and plugins_url() for absolute paths and URLs. More info at: http://codex.wordpress.org/Determining_Plugin_and_Content_Directories.
If you’re going to offer the plugin for download, you should probably include a readme.txt file with the name of the plugin and a description. (You must include a readme.txt file if you want to host your plugin on WordPress’s Plugin directory. See this site for information on the format or use this readme.txt generator.) You may also want to include information on updates and some getting started instructions.
Starting Your PHP File
When making a plugin, you need to start out with a PHP file. It should be named either by your plugin’s name or by a related name.
The file must start out with comment information for WordPress’s parsing engine. If it doesn’t, WordPress will not be able to process it. Use the code below and modify it so it’s for your plugin.
[pbcode id=”FdfrQe8A”/] The minimum information WordPress needs is the plugin name line. The rest of the information will fill in the table on the Plugin management screen. The order of the lines doesn’t matter.
Pick a format for the version number and stick to it to make sure the upgrade mechanism can correctly read the version of your plugin.
The license slug should be a short common identifier for the license of the plugin.
The file must be in UTF-8 encoding.
Many plugin developers include information about the licensing for the plugin directly below the header. Most plugins use the GPL2 license used by WordPress. To indicate a GPL2 license, include the following lines in your plugin:[pbcode id=”TkTzeGxc”/]
Programming the Plugin
Many plugins connect to one or more “hooks”. Hooks work by WordPress checking if any plugins have registered functions to run at that time. If so, the functions run. These functions modify WordPress’s behavior.
For example, before WordPress adds the title of a post to the browser output, it checks to see if any plugin has registered a function for the “filter” hook named “the_title”. If so, the title text is passed through the registered functions and the final result is printed. If your plugin needs to modify or add to the printed title, it can register a “the_title” filter function.
The process for the “action” hook called “wp-footer” is similar. Before the end of the HTML page is generated, it checks if any plugin have registered functions for the “wp-footer” action hook, and runs them.
“Wait, what are action and filter hooks?”
There are two kinds of ho0ks: actions and filters.
Actions are triggered by specific events in WordPress, such as publishing a post or changing a theme. An action is a custom PHP function defined in your plugin and hooked to some of these events. Actions usually do one or more of the below:
- Modify database data
- Send an email
- Modify the generated admin screen or front-end page sent to a browser
How to Create an Action Function
To create an action function, you first need to create a PHP function with the action functionality of your plugin, and put it in your plugin file. For example, if you wanted your users to receive an email whenever you create a post, you might define the following function:[pbcode id=”CBZXh6Bc”/]
For most actions, your function should accept one parameter (usually a comment or post ID). Some actions take multiple parameters. You can also access the global variables of WordPress, and call other WordPress or plugin functions.
Any text output will appear in the page source at the location where the action was called.
It’s good practice to prefix your functions with a special string of characters (like abc_output) to avoid plugin name collisions. You could also just enclose your plugin functions in a class, like the example below which builds off our earlier example:[pbcode id=”4dPQdS7y”/]
The class emailer has a method send that implements the plugin functionality.
The add_action() function outside the class adds the action that tells it to call the send method when a post is published to WordPress. The function send is protected from name collisions by the class. If you wanted to call send, you would need to use a scope resolution operator, like this emailer::send().
This works fine for static methods, but not for an instance of a class. To call a method of an instance, you need to pass the instance as a variable. The following code is the same as the previous example, just modified to work with instances:[pbcode id=”WB4eg15b”/]
To learn more about classes, check out php.net.
Hook to WordPress
After your function is defined, you have to “hook” or register it with WordPress. To do this, call add_action() in the global execution space of your plugin file:[pbcode id=”GqM03GK4″/]
- The name of an action hook provided by WordPress, that tells us what event your function should be associated with.
- The name of the function that you want to be executed following the event specified by hook_name. This can be a standard php function, a function in the WordPress core, or a function defined by you in the plugin file
- An optional integer argument used to set the order in which functions associated with a certain action are executed. Lower numbers mean earlier execution. Functions with the same number are executed in the order added to the action. (default 10)
- An optional integer argument defining how many arguments your function can accept. (default 1)
- Return Value
- The value of the first argument passed to the filter function.
In the above example, we would put the following line in the plugin file:[pbcode id=”ursmNUbN”/]
List of Hooks
You can find a complete list of action hooks here: http://codex.wordpress.org/Plugin_API/Action_Reference
Filters are functions that WordPress passes data through right before taking some action with the data. Filters sit between the database and the browser (when WordPress is generating pages) and between the browser and the database (when WordPress is adding new posts and comments to the database). Most data transfers in WordPress move through at least one filter.
Basically, the process of adding your own filters to WordPress goes like this:
- Create the PHP function that filters the data.
- Hook to the filter in WordPress, by calling add_filter().
- Put your PHP function in a plugin file, and activate it.
Creating a Filter Function
A filter function takes in unmodified data, and returns modified data or a null value (to indicate data which should be deleted or disregarded). If the data isn’t modified, the original data needs to be returned, so subsequent plugins can modify it if necessary.
The first step is to create a PHP function to do the filtering, and put it in your plugin file, which in turn must go into your wp-content/plugins directory. For example, if you wanted to filter out all profanity from your posts and comments, you could define a variable with a list of forbidden words, and the create the following PHP function:[pbcode id=”N9EBeYfY”/]
This function works without a loop because $profanities is an array, and str_ireplace loops through the array for you. The str_ireplace function is used instead of str_replace because str_ireplace is case insensitive.
Hook in your Filter
Now that the function is defined, you need to “hook” or register it with WordPress. To do this, call add_filter() in the global execution space of your plugin file:[pbcode id=”ArMRTaNB”/]
- The name of a filter hook from WordPress, which defines when your filter should be applied.
- The name of a function you want to use for filtering. This can be a standard PHP function, a function in the WordPress core, or a function defined by you in the plugin file.
- An optional integer argument that can be used to specify the order in which the functions associated with a specific filter are executed. Lower numbers mean earlier execution. Equal numbers are executed in the order they were added to the filter. (default 10)
- An optional integer argument defining how many arguments your function can accept. (default 1)
In the above example, we would put the following in the main executing section of the plugin file:[pbcode id=”SjDKH7aU”/]
List of Hooks
You can find a complete list of filter hooks here: http://codex.wordpress.org/Plugin_API/Filter_Reference
Install and Activate Filters or Actions
Now you need to install the plugin and activate it. The PHP function you wrote and the add_action() or add_filter() call need to go into a PHP file together. The PHP file needs to be installed in the wp-content/plugins directory. Then you need to go to the admin dashboard and activate it like any other plugin.
Removing Actions and Filters
You might eventually end up wanting your plugin to disable one of the actions or filters built into WordPress or added by another plugin. You can do that by calling remove_filter(‘filter_hook’,’filter_function’) or remove_action(‘action_hook’,’action_function’).
NOTE: If a hook was registered using a priority other than 10, then you need to specify the priority in the call to remove_action().
WordPress plugins can also add functionality to WordPress by creating custom template tags. Someone who wants to use your plugin can add these “tags” to their theme, in the sidebar, or where ever it’s appropriate.
For instance, a plugin that adds geographical tags to posts might define a template tag function called geotag_list_states() for the sidebar, which lists all states posts are tagged with.
To define a custom template tag, write a PHP function and document it for plugin users on your plugin’s home page and/or in the plugin’s main PHP file. It’s a good idea to give an example of exactly what needs to be added to the theme file to use the function, including the
Saving Plugin Data to the Database
Most WordPress plugins will need to get input from the site owner or blog users and save it between sessions, for use in its functions. This information needs to be saved in the WordPress database, in order to be saved between sessions. There are 4 ways to save plugin data in the database:
- Use the WordPress “option” mechanism – This method is for storing relatively small amounts of relatively static, named pieces of data — the type of data the site owner would enter when first setting up the plugin, and rarely change afterwards. For more info…
- Post Meta (Custom Fields) – This is for data associated with individual posts, pages, or attachments. For more info… and here and look up related functions
- Custom Taxonomy – This is for classifying posts or other objects like users and comments and/or for a user-editable name/value list of data, especially when you want to access all posts/objects associated with a given taxonomy term. For more info…
- Create a new, custom database table – This is for data not associated with individual posts, pages, etc. — the type of data that will grow as time goes on, and that doesn’t have individual names. For more info…
For information on adding an administration panel to view and edit plugin options check out this site.
Updating your Plugin
Overtime, you’ll need (and hopefully want) to release updates and bugfixes for your plugin. When you’re ready to release a new version of your plugin:
- Make sure everything is committed and working. Test it with all WordPress versions your plugin supports. Make sure to test everything that you added and which you already had on it.
- Change the version number in the header comment of the main PHP file.
- Change the version number in the ‘Stable tag’ field of the readme.txt file.
- Add a new sub-section in the ‘changelog’ section of the readme.txt file, briefly describing all changes and bugfixes.
- Commit these changes.
- Create a new SVN tag as a copy of trunk, following this guide.
Give the system some time to work. Then check the wordpress.org plugin page and a WordPress installation with the plugin installed to see if everything installed correctly and WordPress installation shows an update for your plugin.
For More Information:
For more information on and tools for building plugins, check out the following sites:
- http://codex.wordpress.org/Plugin_API (Lots of important information concerning Pluggable functions (an alternate way besides hooks to modify WordPress))
- Francis Yaconiello