Creating WordPress Theme Options With the Theme Customization API

Creating WordPress Theme Options With the Theme Customization API is easy to do. This article shows you how it’s done.

The WordPress Theme Customization API was released with WordPress 3.4, back in 2012. It promised developers a standardized way of adding rich options themes, and users a way of tweaking their website in a, well, user-friendly fashion.

For users, the front-end theme customizer allows you to quickly change the look of your site, and even get a live preview.

The success of this project is debatable but it is being improved upon and is gaining traction. It has been built on a solid foundation and there is no reason not to get started with it.

So let’s take a look at how we can easily add settings to themes using the API.

Here’s what we’re going to cover today:

Building Our Foundation
The Components Of A Theme Setting
Using Setting Values
Live Previews
Encapsulating In a Class
Further Options
Customize the theme customizer.

Building Our Foundation

The key to the customization API is the WP_Customize_Manager class, which can be accessed through the $wp_customize object. We will be using various methods defined in this class to add settings sections and controls within them.

The recommended way of creating theme settings is to encapsulate them in a class. In our initial examples, I will not be adhering to this recommendation to make sure it is clear what is part of the customization API and what isn’t. I will complete the article with a class-based implementation.

Let’s begin by creating a function in our theme’s functions.php file, which will allow us to include our additions in the customizer. This function needs to be hooked to customize_register.

The Components Of A Theme Setting

As mentioned in the example, each item you add to the customizer consists of three parts:

A section must be created to place it in. This section may be one of the pre-existing ones of course
A setting must be registered in the database, and
control needs to be created which is used to manipulate the defined setting

If the separation between a control and a setting seems confusing, think of it like this: When you create a setting you tell WordPress that there is indeed a setting for font color and the default value for this is #444444. In itself, this already means that this setting can be used.

However, the theme customizer needs to know how to manipulate this setting. You could create a text field for it where the user enters new colors manually as “#ff9900” but you could also specify a color control, which would output a color selector. On a database level it will all still boil down to a hex color, but the user-facing side is different.

Creating A Section

The add_section() is used to create sections. It takes two parameters, a section slug and an array of arguments. Here’s an example of how I set up a section for footer options in a theme.

Most of this is pretty self-explanatory. Note the priority, though! This determines the order of the section on the screen. I like to increment my options in tens. If I need to insert a section between two existing sections I won’t need to re-index everything, I can just assign the new one 95.

A couple of custom sections in the theme customizer

Note that sections will not show up when empty. You must add a setting and a control to them before they are shown.

Adding Settings

Settings are created with the add_setting() method. They, too, take a slug as the first parameter and an array of arguments as the second. Take a look below for an example of adding a background color to our section above.

There are a bunch of options we could add here but for now this will do just fine. Note that settings are not tied to section. As I mentioned settings are simply registered with WordPress. It is up to controls, which are tied to sections to manipulate them.

Creating A Control

Controls are put in place with the add_control() method. This method takes a slug and an argument array or it can also receive a dedicated control object. A control object is used for more complex controls such as color selectors or file uploaders.

Here’s how I created the control which modifies the footer background color:

I’ve passed a control object to the add_control() method. This object should be constructed by passing the $wp_customize object as the first parameter, a unique ID for the control as the second and an array of arguments as the third.

Note that the control is where it all comes together. section is set to the id of the section we created and settings is set to the id of the setting.

Once all three have been set up, you should be able to reload the customizer and see your work.

Some custom options added to a custom section in the customizer

Using Setting Values

By default, settings are saved in a theme_mod. Theme_mods are an alternative to the Settings API, they provide an easy way of handling theme-specific settings. All you need to do to retrieve the value of a setting is use the get_theme_mod() function with the id of the setting passed to it.

Let’s add some dynamic CSS to our website by hooking into wp_head and using our saved setting:

Live Previews

Live previews for settings are not enabled by default. To use them you must do three things:

Enqueue a Javascript file that handles the previews
Add live preview support for setting, and
Create the Javascript code to take care of each setting

Enqueueing The Live Preview Script

The only irregular thing about this step is that we need to use the customize_preview_init and we must make sure that ‘jquery’ and ‘customize-preview’ are loaded before our script. Other than that it’s a standard enqueue pointing to a javascript file in our theme:

Add live preview support for setting

This one is pretty easy. In the arguments for our settings we need to define a transport key and set its value to postMessage. Let’s revise our code from before:

Create the Javascript code to take care of each setting

We’ll need to use the wp.customize() function in Javascript. This function should be given the id of the setting as the first parameter, the second is a callback function. Inside we bind a function to the change of the setting and write our code which will take care of the change.

Out of all that we only need to write a line, use this copy-paste template for live preview writing speed:

Encapsulating In a Class

Encapsulating in a class is a good idea because it allows you to write better function names and to make your code more cross-theme compliant, should you have multiple themes in the works. Here’s how I did it for our example above.

Note that everything is exactly the same, all that has changed is the name of some functions and we are referring to methods inside the class instead of functions scattered around in our functions.php file.

Further Options

I highly recommend reading the documentation on the Theme Customization API in the WordPress Codex. It contains a lot of additional settings and ways to work with the API.

Щелкните ниже, чтобы поставить оценку!
Всего: 0 В среднем: 0

Написать комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *