How To Write A WordPress Plugin Tutorial - Step 1 - Overview
One of the biggest advantages of using WordPress is the plethora of plugins available for download. Creating your own can be as easy as writing a few dozen lines of code, or it could take months of work. This tutorial will work through two relatively simple examples to show how to create both of the main types of plugin.
Contents
Pre-requisite Knowledge
Some technical know-how is needed before writing the plugin. You could develop it along the way, however, that will make it more difficult:
- PHP: the programming language used to build WordPress itself and to interact with it is PHP (PHP Hypertext Preprocessor). Some minimal knowledge can be combined with a good reference guide.
- HTML: there is a web interface used for the admin' page - this is written using simple HTML inside the PHP. I use W3Schools as my online reference for HTML; it's also good for JavaScript and CSS.
- Database: WordPress uses a straightforward database and, whilst the interaction with it is abstracted using WordPress function calls, you will need to know how to use tables and the basics of interacting with SQL databases if your plugin stores any data.
If you haven't programmed using a WAMP or LAMP* installation before, now might be a really good time to do it - the knowledge from playing around with one is invaluable here. They're easy to download and install. I started with v2.0h of WampServer on an old PC that was running NT 4 Server (yes it was a while ago...). Since then I've run it on very low spec. laptops and pretty decent desktops - grab any old box and give it a go.
* Apache, MySQL & PHP for either Windows or Linux (respectively)
Once it is up and running you can also run your own local installation of WordPress on it. This is great for using as a sandbox or testing your plugin.
What's In A Name?
Make It Meaningful
The name should, ideally, reflect what the plugin does. Short names are good, aim for between two and four words. For example, if it shows the weather local to the end-user based on their IP address then Local Weather might be a good name. Conversely User's Weather Local To Them As Determined By IP Address would be meaningful, but not exactly catchy. The former would also allow for the plugin to be extended to pick up location by some other means, e.g. facebook locale.
Uniqueness Matters
The name of your plugin must be unique within WordPress. Aside from avoiding the conflict on the WordPress site and in any searches, the plugin name also doubles as the installation directory under wp-content/plugins. If two plugins had the same name then only one could be installed at a time. There are other potential problems as well with duplicate names, we'll get to that soon.
New plugins are being created daily and a name that's available today may not be tomorrow, so it would be wise to choose at least a couple of names for the plugin and to ensure everything that uses this name can be changed easily with a global replacement or two - just in case the name you want is taken by the time your ready to publish.
There are two ways to check for uniqueness of your plugin's name:
- Search the official WordPress plugin repository. However, not all plugins make it into this repository, so...
- Use your favourite search engine, best to include WordPress plugin as well as the plugin name in the search search terms.
Naming Conventions
"Conventionality belongs to yesterday" * - except when there's a good reason for it.
* There's no prize for naming the song that comes from other than the warm glow of knowing The Word.
There are five (5) things that should be uniquely named:
- Installation Directory or File Name (if only one file)
- Database Tables*
- Functions
- Global Variables & Constants
- The Display Name seen by Users
The first four (4) things (above) have to be uniquely named to avoid conflict with other plugins. These must be unique within any given WordPress installation, so the uniqueness of the plugin name should be used as the basis to name the other aspects as well.
The installation directory should reflect the name of your plugin with spaces replaced by hyphens (the latter is a convention and not compulsory). So the standard Hello Dolly plugin, if it used an installation directory, would likely use wp-content/plugins/hello-dolly. If you just have a single file then hyphenate the name it as you would for the directory. In the Hello Dolly case this would result in wp-content/plugins/hello-dolly.php.
The remaining three items can use a single, standard approach*. Create a unique prefix made up of the first letters of the plugin's name plus your initials. Using either the plugin's first letters or your initials on their own runs the risk of it not being unique. Combining them reduces the likelihood of duplication, but there's still no guarantee. Unfortunately there is no directory of prefix's, it would be a lot easier if there were one that was updated as part of the WordPress process for accepting extensions. Such a directory would imply a WordPress standard for naming conventions which also doesn't exist.
* I love standards, there are so many to choose from.
Choosing and sticking with a naming convention has the advantage that if, for some reason, it needs to be changed then this becomes a simple matter of using a global search and replace within your code. Even if you keep the plugin just for your own use it's still a very good idea to use a naming convention to aid uniqueness in case you want to use another plugin that might happen to clash with yours - troubleshooting clashes can be a real pain.
The fifth area where the name is used is in the presentation layers seen by consumers and administrators of the site. This should also be named in a self-consistent manner to make change relatively simple should it be necessary. By this I mean it should be written exactly the same whereever it is used. If, say, you want to change the case so it's all uppercase then do this with CSS.
As a final note, variable names that are local within functions only have to be unique within their own context. As long as they remain within the function (and are not declared as global they can be anything.
Choose The Type Of Plugin
There are two primary types of plugin. The type you choose depends on whether you want your plugin to be called everytime an event happens or only on specific instances of an event. These two types are:
- Action and Filter (everytime); and
- Short Code (specific instance).
At this stage the easiest way of thinking about it is that actions & filters apply to every instance of the selected WordPress action - wherever & whenever it is called (e.g. every blog post) - and the plugin must decide what (if anything) to do, whereas shortcodes only act when a short piece of code is included in a specific piece of content (e.g. in the text of a single blog post).
Side note: it is possible to write a plugin that outwardly appears to be a blend of these types. However, the development reality is two discrete plugins that are wrapped up in one package. They will share some functions, but will otherwise be distinct. As a minimum the shared functions will be those for administration (installation, configuration, update and removal).
Once the plugin is functionally written, the code to hook each of these into WordPress is relatively trivial, however, the broader implications to the plugin are less so. The choice of type will affect how the plugin behaves, including how it delivers its output (if any).
Action and Filter
This plugin is tied to a particular action, e.g. display any page, publish a post, process a user login, write the header, etc.. It is called every time WordPress executes that particular action and often takes the output from that action as its input. Using our Local Weather example this might show the weather in the top right corner of every post.
Actions vs. Filters
A quick pop-quiz: what's the difference between an action and a filter?
Answer: Nothing.
Not convinced? Here's proof there's no difference.
WordPress calls the original action and then the plugin. The plugin must behave in exactly the same way as the original action in terms of the method, type and format of its output. For example, the only thing the_title() does is return its output, therefore any action plugin that hooks to it captures that output, can modify or change it, and then some equivalent output is all the plugin must return. By contrast admin_header() echos its output and any plugin that hooks to it simply adds to that, it does not receive the original output.
Shortcode
With this type of plugin WordPress acts on a specific instance of (generally) a page or post based on a short piece of code embedded by the author or administrator into that post or page. For example, display the weather only on the About page and a post about rising sea levels. WordPress calls the plugin only when it encounters this short code.
WordPress calls the plugin whenever it encounters the shortcode. In simpler plugins the shortcode is manually added wherever it is to be used. Like actions and filters, the output from shortcodes is provided as the return of the function.
Code Beginnings - The Header
Whatever the type of plugin, WordPress looks for, and requires, a header comment in the php. The bare minimum needed is the name of the plugin on its own comment line. This, in the context of the file's location, is what WordPress uses to identify the code as a plugin and list it on the admin page. For example:
<?php /* Plugin Name: Just A Simple Header */ // code goes here ?>
Try It Yourself - put the above code into a file of any name with the extension .php and put that into the plugins directory of your WordPress installation. In the admin plugins page there will now be a plugin Just A Simple Header which you can activate, deactivate and delete - don't worry, it won't do anything.
When you've finished, feel free to throw the above file away.
A fuller discussion of this is in a separate article on headers.