Creating Theme Options using object oriented programming (Part 2)

Object oriented programming part 2

We continue our journey of understanding what OOP is, and how to utilize it in WordPress. We'll create a class, and through it we'll create our sub menu pages.

Disclamer: I noticed a small bug in the code so I updated the code, and all should be working fine. It turns out that wp_ajax hook is picky when it comes to multiple instances of the class :)

Last time we made a foundation for what would be our Theme Options page. We set it up, and created few example settings. Now we want to dig deeper. We want to add multiple submenu pages that have the same structure. As I’ve said before, we could do that by hand, separating each subpage into it’s own file, but since we sort of want the ‘uniformity’, the better solution is to use object oriented approach.

As the name suggest the main interest in oop are the objects. Objects have certain properties that define them, and they can preform certain actions using functions (another word for functions in oop is methods) that are innate to them. You can have many different objects that came from the same class, or that came from different class. So what is a class? Well it is sort of a blueprint of the object. The class will contain all the properties and methods, that will define the object once you’ve instantiated it. Every object is just an instance of the class.
In our ‘house’ model, you can define that house class will have doors, windows, walls and a roof, and you can instantiate many different house objects through it: one house will have 3 windows and a red roof, another will have 5 windows and blue roof.

The real life blueprint example can sometimes be confusing. The programmers aren’t building houses (well, not yet, but with the rise of the 3d printing who knows :D), we’re building digital objects – posts, products, web APIs, or theme settings. These are often not tangible objects, and it can be difficult to grasp their oop side. But the core principles still apply. We’re giving our objects a mean to interact with the real world – to show us input fields and drop downs, and to save or post some data we’ve inputted.

So we’ve said that objects are instances of classes. One great thing in oop is that you can even extend the functionality of the existing class. In our house model, that means that we can extend our house class, and call it HouseWithGarden and add a garden property. In a more real world example, that would be extending the Menu Walker class, and adding sidebars or megamenu to it.

The benefit to oop in my opinion is the fact that all our code (for a certain object) is neatly contained within a class, and you can use, or inherit, certain properties from the existing classes. We are breaking our code into many logically connected pieces and we’re then interconnecting those pieces.

For ore in depth explanation about OOP in WordPress I’d recommend reading great blog from Tom McFarlin on code.tutsplus.

Creating Theme Options subpages

When ever you want to create your digital object, you need to figure out what your object must contain, and how will it behave. I personally like to do this on paper, because I’m used to doing things with pen and paper, you do what ever works for you the best.

For our Theme Options sub pages, we’d like to have the ability to change names of course, and a certain default settings that will appear on our pages. These are kinda basic necessary options that we want, the backbone on which we will build our sub pages. We can figure out what kind of options do we want to show: input fields, textareas, select drop downs, menu pages, color picker, image uploads etc. We can add small descriptions under every field, so that the user knows what the certain option is for. You can literally build anything that you think can be important for Theme Options to have.

So when creating our sub pages, we’ll instantiate a class called SettingsSubageBuilder which will contain a name of our sub page, and an array of settings that will appear on the subpage. The way we create our array is also important. In this case I’ve added two major keyes to the array: description, and settings_control. The description will have a general description of the sub page which will appear under the title, and the settings_control will be another array which will have controls (another array), consisting of name, control_type and description. Of course depending on control type you’ll customize the control array. For instance the header settings array will look like this:

We need to have all this in mind, so that we know how to handle this in our class. As I’ve mentioned, the object will receive the name and this array as arguments, and from it it will create our page. Let’s start building our class. in php creating a class is easy, just add class and name in CamelCase (Pascal Caps) and add curly brackets, and that’s it. A class is created. Empty one, but a class nonetheless. Since we want to input some stuff into our class initialization, we need to use magic method called __construct(). What it does is that it will automatically be called when ever an object is first created. In it we can add our actions as well. Magic methods will allow your class to ‘react’ to certain events, like construction, destruction, sleep etc. And they always begin with two underscores in front of their names. So when we create our sub page, we can pass in the necessary parameters that will be injected to __construct() method and with that will make those parameters available for us to use later on in our methods. Continuing to work in our theme-settings.php file we’ll have

We’we added two properties – sub page name and the array that will create our html. Notice the private and public keywords. They will describe the visibility of a property or a method. As described in the manual class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited classes. Members declared as private may only be accessed by the class that defines the member. So be careful when declaring the visibility of your properties and methods. We’ve declared the properties as private, and the magic method as public. This is because the properties that we declare within the class, should be only used within this class, and the construct method can be used even if we extend the SettingsSubpageBuilder class.

In our __construct() method, we referenced to our name and settings, and we also added two actions – one will be the action to add the sub menu page, and other will be for the ajax save. The construction array( $this, 'function_name' ) is just the way to callback the method defined in the class that you’re in. You’ll see the methods create_submenu_pages and twentysixteen_all_settings_save in a little while.

Note: Upon inspection it turned out that instantiating many classes at once and defining wp_ajax hook doesn’t work too well. For some reason if you put the same name for the ajax action, the ajax callback function will only recognize the first one that got instantiated, and thus the saved options will only be saved in the first instance of your class (there will only be one option settings in your wp_options table). In other words, when you’d save other options from the sub pages, they would overwrite the first settings over and over, and you’d have a problem. We’ll need to modify the JavaScript a bit, but that will come later on. This is why we need to define $ajax_hook variable that will change with every option name.

Next thing that we want is to add a method that will add our subpage

We want to have page hook that will be unique for each instance of our class, so we’ll convert our sub page name to lower case, and we’ll replace empty spaces with underscores. Then we’ll use WordPress built in function add_submenu_page(). This will take care of our subpage. Notice that we’re self referencing to sub page name using $this keyword. Next we want to create a method that will create our html elements. We want our method to take two arguments – default value defined in the array, and saved values from the database. The method looks like this

First we define our names, control types, descriptions all from the default values, and we take the actual saved value from the $saved_values array. Then, based on the control type we’ll output the desired html of the control. The idea behind this is that we will loop through our control array we defined at the top, through the controls and for each one we’ll output the desired field. Here I’ve added the controls that appear in the array.

The next method is the method which will render our sub page. We want our sub page to look like the Theme Options page, so it will have page title, description, save button, and our settings which will be rendered according to the fact that we may or may not have something saved in our database.

The last method that we need is the ajax callback function

Be sure that you validate your saved fields, verify the nonce, and sanitize text before putting it into the database. This is very important security aspect, because you never know when you could get a security breach. To our settings-style.css we can add

and for our image

To separate titles from the options a bit. You can style it further if you want to, but for the sake of the demonstration this will do.

Now to add your subpage we need to create a new instance of the class

You’ll end up with something that looks like this:

Theme Settings Header Options screen

Theme Settings Header Options screen

Now we need a way to save our settings, add colorpicker and way to upload images. We’ll need to modify our enqueued scripts a bit

We’ve added color picker, and media upload. In our settings-custom.js file we’ll add few controls:

We’ve added ajax save function, color picker and a way to add image by calling the WordPress media uploader. With that enabled, our settings page will look like this

Theme Settings Header Options screen finished

Theme Settings Header Options screen finished

So now that we’ve finished this, what can we do with it? Well the rest is simple – you want footer options? Specify the footer settings aray and instantiate a new class:

Theme Settings Footer Options screen

Footer options were created by creating a new object.

We’ve only specified two things and we got a whole new page. Much simpler than writing everything from scratch, no? Here’s the finished file in full

And the css (JavaScript file is given above)

Now all you need to do, when calling the options from the database is to pull it with

Remember that you’ve saved your option in the ajax callback function that used your theme slug, and the name of the option sub page (lower caps and underscore instead of space).

So this is it, I hope you’ve learned something new, and that object oriented programming doesn’t seem so scary now. It’s a great way to solve certain problems. Of course this is just a small part of what oop is capable of, but it’s a great start for someone who is new to it. If you have any questions, leave them below, and as always: happy coding :)


Also published on Medium.

Join the Discussion