An Introduction to Object-Oriented Code for WordPress Plugins
Object-oriented programming can be difficult to wrap your head around but is important to learn and understand if you want to grow your skills in plugin development.
Last year, I wrote about using object-oriented programming (OOP) in plugins through a specific example. Since that article contained a lot of advanced code, I thought it would be a good idea to write about OOP for beginners.
In this article, I’ll show you a couple of handy tricks you can use to make your plugins object-oriented, which will decrease the chances of code clashes and start you on the path to writing better and more modular code.
Note: This article is about object-oriented programming, an advanced style of coding, and some of the information is incomplete or has been intentionally simplified to suit beginners. The goal is to ease you into the core concepts of OOP, not help you become an expert overnight. Experiment and learn as much as you can and you’ll become proficient in OOP in no time!
What is Object Oriented Programming?
On a very basic level, OOP is another layer of abstraction. If you’ve written PHP for WordPress before, you’ve already seen abstraction in progress. Instead of writing lines of code one after the other, OOP uses constructs such as functions. Functions can take code and make it a lot more modular. Here’s a quick example:
I manually created an excerpt from the content. Not a big deal, but imagine doing this every time you displayed a post. Not only would it be a headache, but what if you wanted to change the excerpt length? It is hardcoded to be 250 characters at the moment, but you would need to go through each and every excerpt by hand. This is why functions are so useful – WordPress would take care of this problem using the
the_excerpt() template tag.
OOP is a new layer of abstraction, which is very similar to functions initially. In this tutorial, we will be creating a class, which is kind of like a container for functions.
Let’s get stuck in.
Writing Your First Class
Let’s create a class named “Post.” The purpose of this class will be to manipulate blog posts, like so:
The class contains three simple functions at the moment: one function is for getting excerpts, the second function displays excerpts, and the third function simply echoes titles. Currently, the class is just a collection of functions as promised. However, it doesn’t really do anything.
To show the power of classes we’ll need to take a look at a special function named
__construct(), a special variable named
$this, and variables defined within classes.
When you create a class, the intention is usually, but not always, to create multiple objects with it. You can create multiple posts with the existing
Posts class, for example. Let’s take a look at how to do it:
There’s a lot to see here, so bear with me for a moment! Whenever you create an object using a class (in the code above this is the
$post = new Post( $postdata ) part), the constructor function is automatically executed.
Arguments passed to the new class will be available in the constructor. You use the data received from the
$postdata array to populate the value of two variables defined within the class.
I assigned the title to
$this->title and the content to
$this is a special variable that points to the class itself. Whenever you write code inside a class you can use
$this->property to refer to a defined variable or
$this->function() to refer to a function defined within the class.
Note: functions within classes are called “methods” and variables defined within a class are called “properties.” I’ll be using the proper terms from now on.
I find that the best way to understand how classes work is to follow along the code once you’ve instantiated the class and invoked a method. When you create a post the constructor is run. You’ve already seen how this populates our two properties.
Next, we invoke
$post->the_excerpt(). Now we use the object variable, not
$this when we are writing code outside of the class itself. This function simply echoes the return value of another function:
$this->get_excerpt(). Since we call this function using the
$this keyword we know we need to look for it within the class.
get_excerpt() function doesn’t need to be passed any content because it takes the content from the defined
$content variable. It then runs our little excerpt and returns a string.
Before we look at how to use classes in plugins, let’s do a quick recap.
For the moment, classes are wrappers for functions. We define them by typing
class followed by a class name. We write functions (named methods) and variables (named properties) within curly braces.
If we are writing code within the class we can refer to properties and methods defined in the class with the
We can create an object by using the
$object = new class( $params ) syntax. At this point, the constructor function is run within the class, which we can use to populate properties if needed.
If we want to perform functions on our object available in the class we use the object variable.
If you’d like a bit more information about objects, take a look at tutsplus.com or many other OOP PHP tutorials.
Using Objects in Plugins
Since classes encapsulate code they are great for preventing code conflicts. I could well have a
get_excerpt() function in my class within a WordPress plugin, even though WordPress has its own function with the same name.
OOP is great because if forces better practices on you as a coder. Your code will become easier to read and better organized as a result.
Since OOP is meant to be extendable easily with child classes and other mechanisms, your work is potentially more modular.
When written well, OOP is almost always a better solution. To reap the benefits you usually need a codebase larger than a few lines but a simple WordPress plugin is perfect practice.
When starting out, I recommend using objects as simple encapsulation mechanisms. Here’s a quick example of a plugin that adds “Written by someone awesome” after each post:
I love how putting code inside objects automatically makes your hook calls more organized. The pattern is that you should put all your action and filter hooks in the constructor function and then write the functions underneath.
If you follow this pattern, remember to use an array as the second parameter of the
add_action() functions. The first property should be
$this and the second should be the function’s name.
Once you’re comfortable with this technique you can start to play around a bit with objects. You could create one class for handling the front-end output of a plugin and another for backend changes.
Take a look at this plugin, which modifies a WordPress website to show all posts ordered by comment count:
This example may seem a bit over-complicated (because it is), but the point I’m trying to make is that it makes sense to separate your code into well-defined areas. It makes extending your work and modifying it later on a lot more straightforward.
A Complete Example
If you’re interested in a more elaborate example, take a look at the WordPress Plugin Boilerplate project. It is an effort to place plugins on proper code.
I’ve used it in a number of projects and I can heartily recommend it, especially for plugins that require a higher level of complexity.
WordPress needs better-coded plugins and one solution is using object oriented code. It makes your code more readable, better organized and of higher quality in general. You can make your work easily extendable and if you’re an experienced OOP coder it will practically document itself.
Have you ever used OOP in a plugin? Has this tutorial inspired you to get started? Let us know in the comments below.Tags: