php_wp_plugins_logo
CMS - Wordpress - Coding - Databases - PHP

Introduction to WordPress Plugin Development with PHP

WordPress is the most popular content management system on the web. Over 60 million websites use WordPress, from your neighbor’s blog about goldfish to premium enterprise sites like CNN and Time. Like PHP, the scripting language that it is built upon, WordPress isn’t perfect, but if you work in PHP long enough, you’re going to need to know how to work in WP.

One common job for a PHP programmer working with WordPress is to develop a custom WP plugin. Plugins are modules that add onto WordPress’ core code, allowing it to expand its functionality without making the standard package any bulkier than it already is. In this tutorial, I’m going to teach you how to write a basic WP plugin in PHP. I’m assuming that you have some basic knowledge of PHP already. If you’re starting from scratch, I recommend going through our Introduction to PHP tutorial first.

Installation and Setup

Obviously, to build a plugin for WordPress, you’re going to need to set up WordPress first. Luckily, it’s one of the most painless installations in software history. As long as you have PHP and MySQL installed on your host or machine, just follow the instructions here and you’ll be up and running in no time.

For the purposes of this tutorial, we’re using the most up-to-date version of WordPress (currently 3.8.1) and the basic theme that ships with that version, called “twentyfourteen”.

To start out with, the front page of your new WordPress site should look something like this:

php_wp_plugins_start

Understanding WordPress Hooks

As I mentioned at the beginning, the developers of WordPress want to make the software as flexible and widely usable as possible, without adding too much to the already large core code that every new WP user downloads and installs. Plugins are the answer, but every plug needs an outlet. The places in the core WP code that are built to accommodate plugins are called “hooks”.

There are two kinds of hooks, actions and filters. Actions are triggered by events, like activating a theme or publishing a post. A great example of an action-hooked function would be one that emails the site administrator every time a new post is published by any writer on the site. On the other hand, filters are functions that take in data, process it, and output it in a different form. An example of a filter-hooked function would be a language filter that sanitizes curse words on a user-generated content site.

The Hello World Plugin

Before we do anything fancy with plugins, let’s make the simplest possible one. The following plugin will add the words “Hello World!” to the beginning of every post on a website. Obviously, this isn’t something you probably want on your site, but it serves as an example. First, create a new PHP file and call it helloworld.php. Fill it with the following code:


<?php

/**
 * @package WP Hello World Plugin
 * @version 1.0
 */
/*
Plugin Name: Hello World
Plugin URI: 
Description: Plugin Example for WordPress
Author: Your Name Here
Version: 1.0
Author URI: 
*/

// Functions
function helloworld ($content) {
  $newcontent = "Hello World!<br /><br />".$content;
  return $newcontent;
}

// Hooks
add_filter( 'the_content', 'helloworld' );

?>

As you can see, this example uses a filter hook, rather than an action. Place this file in the /wp-content/plugins directory of your WordPress installation. Then activate it by going to the Plugins section of your WordPress admin dashboard and clicking “Activate” under the plugin listing for “Hello World”.

Now, that post on your front page should look like this:

php_wp_plugins_hw

Note the addition of that (admittedly pretty boring) line of text at the top of the post. Since you only have one post on this new site, you might only see this once, but if you had 1000 posts, this text would appear at the top of all of them. Even for such a simple function, that’s pretty powerful distribution. Now let’s use it for something a little more interesting. Before we move on, deactivate that Hello World! plugin, and watch the message disappear from all your posts.

Connecting to the Database

One thing that is really nice about working inside WordPress, as opposed to building an app from the ground up, is the ability to piggy-back on WP’s established functions. My favorite example of this is database connection. Since a plugin runs somewhere between the beginning and end of WordPress’ regular operations (loading a page, publishing, etc), the database connection is already open. All you have to do is use the right variables and functions to use it, and we’ll cover that in our next code example.

A More Useful Plugin

Assuming you don’t want every post on your website to display that same planetary greeting, let’s make that bit of text say something a little more useful, without having to change the hook at all. Let’s build a plugin that tells users the length of the post, and how long it should take them to read it.

Start a new PHP file, and call this one readtime.php. Fill it with the following code:


<?php

/**
 * @package WP Read Time Plugin
 * @version 1.0
 */
/*
Plugin Name: Read Time
Plugin URI: 
Description: Plugin Example for WordPress
Author: Your Name Here
Version: 1.0
Author URI: 
*/

// Functions
function readtime ($content) {

  global $wpdb;
  global $post;

  $getpost = $wpdb->get_var($wpdb->prepare(
      "SELECT post_content FROM wp_posts WHERE ID = %d", $post->ID));

  $wordcount = str_word_count($getpost);
  $minutestoread = $wordcount / 250;

  $newcontent = "This post has ".$wordcount." words. 
      It will take the average reader ".$minutestoread." minutes.
      <br /><br />".$content;
  return $newcontent;
}

// Hooks
add_filter( 'the_content', 'readtime' );

?>

Your first post on your WordPress front page should now look something like this:

php_wp_plugins_read

Let’s go through some of the new code in that plugin. First, there are two global variables that need to be declared in the beginning of our function: $wpdb and $post. These are WordPress-specific variables that respectively hold data about the database connection and the current post. You’ll also notice that the query looks a little different from a regular PHP/MySQL database query. That’s because WordPress has functions built in both to sanitize and run queries. $wpdb->prepare() is a function that sanitizes a query and makes sure there is no potentially harmful code in it. $wpdb->get_var() runs the query and loads the variable being selected (in this case, the content of the post) into a variable. It’s a handy function that saves a few lines of code each time it’s run.

Now, before any WordPress veterans raise their hand, yes, there is a faster way to access post data. But $wpdb->get_var() is a function that can be used for any database table, whether it’s a part of the basic WordPress set of tables or one the user adds themselves. For that reason, I feel it’s a better one to teach at this point.

Lastly, we determine the length of the post content with the core PHP function str_word_count(). According to a quick Google search, the average person reads about 250 words per minute, which is where we got the number to convert word count into reading time.

What’s Next?

In this tutorial, we’ve built the most basic possible WordPress plugin, then built on it to create something that might actually be useful to a real site. I’ve also introduced you to the $wpdb set of functions for piggy-backing on WordPress’ database connection. Now, it’s time for you to play with the code and make it do what you want. Experiment with new hooks and functions, and stretch what you believe a WordPress plugin can do. Happy programming!

About the author

Ian Rose is a web developer, blogger, and writer living in Portland, OR. In his day job, he develops WordPress plugins and custom PHP solutions, focusing on nonprofit clients. By night, he attempts to write both fiction and nonfiction. Ian's site is Seaworthy Web Solutions

Share this post

Leave a Comment

Subscribe To Our Newsletter