So you want to write a WordPress plugin

Plugin Code Sample

Do you think you want to write a plugin to enhance your WordPress site? Looking for a how-to guide to get you started? Let me tell you my approach.

Why write a plugin?

I’m not going to get into the philosophy of plugins – what makes for a good plugin, what should be in a plugin vs. what belongs in a theme, plugin programming best practices, etc. Those will be touched on in future posts. Today I’m writing a how-to article describing how to write a simple plugin.

By the way, this plugin will not qualify for inclusion in the WordPress Plugin Repository. That, too, is a topic for another day.

Focus on the functionality first

At this point I’m going to assume you’ve got a good idea of what you want to do. Have you looked through the WordPress Plugin Repository to make sure someone else hasn’t already done it? There are thousands of plugins in the repository, so there’s a good chance someone has already created your plugin for you. Probably several someones. Yes, searching through the submissions can be a real pain, but it’s less painful than developing software from scratch.

The more specific your idea is, the less likely you are to find what you’re looking for in the repository, but it’s still worth the search. Even if what you find is simply close to what you want, get it, for then you can modify the code to do exactly what you want it to do.

You do know PHP, don’t you?

The language of WordPress software – the core, plugins, and even themes – is php. This makes it easy to mess up modify, and also means that if you speak php you can tweak any of it to do your bidding. If you don’t, well, either learn the language or hire someone to do it for you. Even commercial plugins and themes are in php, so the only thing keeping you from tailoring them to your own needs is copyright restrictions (which can be significant, but I’m not going to get into that here).

Step 1 – write the function

Enough procrastinating! Let’s get down to code.

I don’t know what your function is, so I’m going to illustrate things with a bit of my own. This is a function to create a random writing prompt. That’s a sentence composed of three randomly chosen pieces, in the form of

A first thing, a second thing, and a third thing.

Why this? Why not? I send out tweets composed of these every day to a bunch of writers looking for inspiration to get them past a bit of writer’s block. Using this function I can simplify my morning routine.

To start with, we need a database of “things”. Let’s start with an array that looks like this:

[php] $lines = array(
‘twelve drummers drumming’,
‘eleven pipers piping’,
‘ten lords a-leaping’,
‘nine ladies dancing’,
‘eight maids a-milking’,
‘seven swans a-swimming’,
‘six geese a-laying’,
‘five gold rings’,
‘four calling birds’,
‘three french hens’,
‘two turtledoves’,
‘a partridge in a pear tree’
);
[/php]

I’m going to leave this as a global for the moment. Next let’s write the basic function:

[php] function my_func() {
global $lines;

$index1 = rand(0, count($lines) – 1);
$index2 = rand(0, count($lines) – 1);
$index3 = rand(0, count($lines) – 1);

while($index2 == $index1) {
$index2 = rand(0, count($lines));
}

while(($index3 == $index1) || ($index3 == $index2)) {
$index3 = rand(0, count($lines));
}

$first = $lines[$index1];
$second = $lines[$index2];
$third = $lines[$index3];

$str_out = ucfirst($first) . ‘, ‘ . $second . ‘, and ‘ . $third . ‘.’;

return ‘<blockquote>’ . $str_out . ‘</blockquote>’;
}
[/php]

The first part of the function brings the $lines array into the scope of the function, and creates three random indexes into it. (Remember that arrays in php start with 0.)

Then there’s a little code to make sure we don’t repeat the same piece twice. Next we get the pieces and assemble them into a sentence ($str_out) with the first letter capitalized, commas and “and” as needed, and a period at the end.

Finally we return the sentence within a blockquote tag (because this is, after all, going into a page on the web).

Yes, I’ve tested this code, and it works.

Step 2 – make it into a plugin

The single most important part of a plugin is the comment block at the top of the file. It’s what tells WordPress that this is a plugin, and provides the information that’s displayed on the Plugins page in the Dashboard. If all you have in your file is this, you have a valid plugin. It won’t do anything, but so what?

The comment block looks like this:

[php] <?php
/**
* Plugin Name: Random Writing Prompt v1
* Plugin URI: http://kurtschweitzer.com/RWP
* Description: Creates a shortcode that can insert a random writing prompt into a post or page.
* Version: 1.0
* Author: Kurt Schweitzer
* Author URI: http://kurtschweitzer.com
* License: GPL2
*/
[/php]

Oh, while you’re at it, you’d better think of what you want to name the plugin file. A good name is something similar to the name of the plugin as shown in the comment block. In my case I called it rwpv1.php.

Even if all you have is that, you’ll see this on your Plugins page:

RWPPlugin

Step 3 – make it functional

There’s one other thing you need to make your function actually do anything – a hook.

Hooks are the secret to making a plugin work. WordPress has a whole list of hooks to connect plugins with the WordPress core so that the plugin actually does something at the right time whenever WordPress displays a page or post. We will get more into the hooks in a later post. Today we’re just looking at one: add_shortcode().

This is the line we need to add to our php file to make it a functional plugin:

[php] add_shortcode(‘RWPv1’, ‘my_func’);
[/php]

This tells WordPress that every time it encounters a [RWPv1] shortcode, execute my_func() and display the returned string instead of the shortcode.

What is a shortcode? It is command entered inside square brackets [command]. Every time WordPress encounters a square bracket in your text it looks to see if the contents can be interpreted as a shortcode command. If so it executes the shortcode, otherwise it simply displays the text as usual.

In my example, the command is RWPv1. When the [RWPv1] shortcode is encountered, the my_func() in my plugin will be executed.

Step 4 – Use it in a page or post

I’m not going to create a separate post for this (yet), instead I’ll just demonstrate it here:

Three french hens, five gold rings, and eleven pipers piping.

If the plugin is active the above shortcode is replaced by a random writing prompt. Deactivate the plugin and the shortcode is visible.

To get a different random writing prompt, simply refresh the page. (This will drive your page views up, but we’ll address that in a later post.)

In case you want to see it all put together, here’s the complete code:

[php] <?php
/**
* Plugin Name: Random Writing Prompt v1
* Plugin URI: http://kurtschweitzer.com/RWP
* Description: Creates a shortcode that can insert a random writing prompt into a post or page.
* Version: 1.0
* Author: Kurt Schweitzer
* Author URI: http://kurtschweitzer.com
* License: GPL2
*/

$lines = array(
‘twelve drummers drumming’,
‘eleven pipers piping’,
‘ten lords a-leaping’,
‘nine ladies dancing’,
‘eight maids a-milking’,
‘seven swans a-swimming’,
‘six geese a-laying’,
‘five gold rings’,
‘four calling birds’,
‘three french hens’,
‘two turtledoves’,
‘a partridge in a pear tree’
);

function my_func() {
global $lines;

$index1 = rand(0, count($lines) – 1);
$index2 = rand(0, count($lines) – 1);
$index3 = rand(0, count($lines) – 1);

while($index2 == $index1) {
$index2 = rand(0, count($lines));
}

while(($index3 == $index1) || ($index3 == $index2)) {
$index3 = rand(0, count($lines));
}

$first = $lines[$index1];
$second = $lines[$index2];
$third = $lines[$index3];

$str_out = ucfirst($first) . ‘, ‘ . $second . ‘, and ‘ . $third . ‘.’;

return ‘<blockquote>’ . $str_out . ‘</blockquote>’;
}
add_shortcode(‘RWPv1’, ‘my_func’);
?>
[/php]

I plan on coming back to this, but in the meantime this is the simplest plugin example I can think of that actually does something other than reformat text. Enjoy!

Did you like this? Take a second to support me on Patreon!