The Way of the Object: Writing Your Next Plugin

WordPress unknown plugins

Author :  

WordPress unknown plugins
  • Recruit
  • Recruit

There are two main paradigms when you are writing your own plugin: in a functional or object-oriented style. One is not better than the other, but there are multiple advantages in making your plugin object-oriented:

  • Functions are protected under namespacing
  • For larger projects, creating classes and creating instances keeps things tidy and easy to reference

Getting Started

Before starting, if you would like, you can check out the Plugin Boilerplate and learn from that project as well. The first step is to declare a class:

You can name the class whatever you want. The next step is to use a constructor class, the data within the constructor plugin will . Think of it like this: the class is the blueprint of the house, the constructor function represents the construction crew members. Finally, the object is the house. (Analogy Credit: Tuts+) The constructor function looks like this:

That’s right, those are two underscores. Here’s what it looks like at this point:

You should add your text domain (for translation), register scripts, enqueue scripts and declare any variables and functions within the constructor function. For example:

You can also declare your own variables or constants in the constructor function. Like so:

The main difference between public and private variables are:

  • Public variables are available/visible to all classes
  • Private variables are only available/visible to the classes in which they belong

Source: http://www.javacoffeebreak.com/faq/faq0002.html

This means that you can use public variables in other classes/files, while the same cannot be said of private variables. Now it’s time to write our own functions! Let’s enqueue the plugin’s javascript files! But before that, let’s take a look at the action hook:

Normally, when writing a non-object oriented plugin, we would be writing it like this:

However, in this case, we need to tell WordPress which class it needs to work with. For that reason alone, we can use the $this variable to refer to the TestPlugin class. Let’s move on to enqueueing the theme.

Public functions work in the same manner as the variables discussed earlier. It’s just a prefix describing the variable/function right next to it. Finally, let’s create the instantiation of an object. To accomplish this, you will just need to add the following line outside of the class:

The line will initiate and execute the constructor function within the class. Referring to the house/construction worker example mentioned previously, this is the workers being given an order to start the construction.

Let’s take a look at the whole file:

There you have it! If you have any questions or concerns, feel free to leave a comment below. Thanks for reading!

  • sns