Customizer API: Custom Control

In the previous blog post from these mini series, we’ve given a rough explanation about what Customizer API consists of and the reasons to use it. In this blog post we’ll take share a deeper insight on custom control.

Customizer API gives us a lot of custom control we can use by the default. The objects we can use by the default are:

  • WP_Customize_Control
  • WP_Customize_Color_Control
  • WP_Customize_Upload_Control
  • WP_Customize_Image_Control
  • WP_Customize_Background_Image_Control
  • WP_Customize_Header_Image_Control
  • WP_Widget_Area_Customize_Control
  • WP_Widget_Form_Customize_Control

By creating WP_Customize_Control object with type attribute we can choose between:

  • text
  • checkbox
  • textarea
  • radio
  • select
  • dropdown-pages
  • email
  • url
  • number
  • hidden
  • date

For radio and select controls it’s necessary to define choices attribute with the array that will have options the administrator can choose from.

Custom control class

For example, we’ll make a custom control that will manage our theme’s layout. The first thing we need to create is a class that will be later initialized.

Style

You can see in the class above that we’ve enqueued customize-control-layout style. Therefore, we now need to register style on admin_enqueue_scripts action. The style for our example looks like this:

JavaScript

In the control class you can see that we’ve enqueued customize-control-layout script. We need to register that script on admin_enqueue_script action. For this example, we created layout choosing functionality in the out script:

Customizer

We’ve made a class for our control that we’ll use for our option of enabling administrators to change the theme layout. We’ve also stylized it and added selection functionality with JavaScript. Just like we explained in the previous blog post, we’ll now add the section and layout control in the Customizer option.

We will add sj_global_layout setting, layouts section and sj_global_layout control for within the section in WP_Customize_Manager object.

Live Preview

With every layout change, we’ll add one of the classes layout-none, layout-left or layout-right to body element. We’ll handle changes with CSS (this part differs with each theme so it is up to you). The customizer.js (explained in the previous blog post) will be similar to this:

Template

To apply the current settings for website visitors, it’s necessary to change the way we define the body element in the header.php:

Summary

We hope that these two blog posts have explained the Customizer structure and the easiness of upgrading it with our own controls. It’s up to you to use it on your own projects with endless possibilities. To finish up, we’ll mention some of the options that will be easier with the Customizer:

  • Font chooser
  • Color schemes
  • Social buttons
  • Copyright
  • Width slider