Theme Development

Digging Into the Theme Customizer: Practicing II


In the previous post, we examined the Theme Customizer's component in actions. In this part, I would like to show you three additional things that I see as important for you about Sanitization, Transport, and some Extended components in the Theme Customizer.

Before reading this, I recommend that you review the previous articles in this series.


Sanitizing data is not a new problem, but it’s an important thing that should be carefully considered. Data sanitization allows you to be sure that your data is properly validated.

In the Theme Customizer, in order to validate data, we have to have a validating function first, then we need to define that function as the value of the sanitize_callback property when adding a new setting.

In the previous article, I created a group of settings including a number, email and added an input field. We will use them for the following examples.

I would write a simple function validating that the input value is an integer and bigger than zero:

function check_number( $value ) {
	$value = (int) $value; // Force the value into integer type.
	return ( 0 < $value ) ? $value : null;

And remember to declare the value of the sanitize_callback attribute when creating a setting. Replace the old declaration of the wptuts['number'] setting with:

	$wp_customize->add_setting( 'wptuts[number]', array(
		'default' => 0,
		'type' => 'option',
		'sanitize_callback' => 'check_number'
	) );

We have just created an simple guarantee ensuring the input value must be of type integer and larger than zero.

Essentially, the check_number function will be hooked into a filter whose task validates a newly submitted value of the current setting. The hooked function take an argument from calling this action, $value in this case, that contains a new data value.

Our snippets will examine this variable, whether or not it is expecting our data, and if so, return it; otherwise, it will return a value of NULL and then the data will be rejected and will not be saved.

In the second example, I would like to show you how to validate an email field. Below is a validation function:

function check_email( $value ) {
	return ( is_email( $value ) ) ? $value : null;

Also need to define the sanitize_callback function for the wptuts['email'] setting.

	$wp_customize->add_setting( 'wptuts[email]', array(
		'default' => '',
		'type' => 'option',
		'sanitize_callback' => 'check_email'
	) );

is_email is a built-in WordPress function that verifies that an email is valid.

By default, the Theme Customizer also has some sanitization functions. A sanitize_hex_color_no_hash function that ensures the data must be a hex color without a hash, And another JavaScript callback function is maybe_hash_hex_color which guarantees the hex color must be prepended by a hash since this value will be used in JavaScript code.

You could to refer our post about Data Sanization, or Data Validation in the WordPress Codex.


Recall from the previous article what we discussed about the concept of settings' transport property. You already know transport has two values, the former which is also the default is refresh, and the latter is postMessage. Referring back to the previous article to take a look at the differences of these.

Transport is how data is transferred.

All previous examples, transport property has the value of refresh as default which means every time a set of changes occur, the Preview Frame on the right-hand will be automatically reloaded.

Note that the entire frame and its contents are updated. Whereas, if a setting is formed as postMessage, it will instantly change the value of it at each time it changes, forcing the new content to the Preview Frame right after they occur.

Create a new setting with the id wptuts[footer]:

$wp_customize->add_setting( 'wptuts[footer]', array(
	'default' => 'Copyright &copy; 2012 WPTuts+',
	'type' => 'option',
	'transport' => 'postMessage'
) );
$wp_customize->add_control( 'wptuts[footer]', array(
	'label' => 'Footer content',
	'section' => 'wptuts'
) );

Then add the content of this setting to the TwentyEleven's footer. Since this theme has an action within it, simply add a function to this action:

function wptuts_footer() {
	$home = home_url();
	$wptuts = get_option( 'wptuts' );
	$footer = $wptuts['footer'];
	echo "<a href='{$home}'>{$footer}</a><br />";
add_action( 'twentyeleven_credits', 'wptuts_footer' );

The wptuts_footer function will print the content containing a credit link at the end of the website. Because postMessage works based on JavaScript techniques, we have to do one more step to make it work properly.

Add the below code right after adding the control of wptuts[footer] setting.

function wptuts_js_footer() {
	wp_enqueue_script( 'wptuts-js-footer', plugins_url( '/js/wptuts_theme_customizer.js', __FILE__ ), array( 'customize-preview' ) );
add_action( 'customize_preview_init', 'wptuts_js_footer' );

Then put the following JavaScript into a file called js/wptuts_theme_customizer.js:

( function( $ ){
	wp.customize( 'wptuts[footer]', function( value ) {
		value.bind( function( to ) {
			$( '#site-generator a.wptuts-credits' ).html( to );
		} );
	} );
} )( jQuery );

wp is a JavaScript object, its customize method takes the value of the setting's id, wptuts[footer], and binds that value to the content of the matched HTML element, #site-generator a.wptuts-credits, in this case.

Check the result:




Try to change any value, and see the way postMessage works. It doesn't reload the whole Preview page, just changes the value immediately of some little pieces of the page.

Tip: Keep an eye on the browser's status bar or address bar when trying two of these properties, you might see the difference.

Extended Component

Perhaps you knew that the control's type has some value like text, checkbox, radio, or select helping you to render appropriate form's content; however, not all of them cater to our needs. Therefore, extending current controls to do additional work is necesssary.

WordPress supplies useful, extended components. Some of them are Color and Upload Images forms, for example. By reusing these components, we don't need to add many external things complicating our website. You also know that every component in the Theme Customizer is an object. These extended components are too, since they are extended from basic classes.

Color Form

Let's create a new setting with id wptuts[color]:

$wp_customize->add_setting( 'wptuts[color]', array(
	'default' => '#000000',
	'type' => 'option',
	'sanitize_callback'    => 'sanitize_hex_color_no_hash',
	'sanitize_js_callback' => 'maybe_hash_hex_color',
) );

Remember to register a control for it, the control in this case has some differences from all previous ones:

$wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'wptuts[color]', array(
	'label'   => 'Color',
	'section' => 'wptuts',
) ) );

Some important things to note are:

  • WP_Customize_Color_Control class is extended from WP_Customize_Control. It’s more specialized in the task of creating a form input with a color picker. Of course, it renders its own form element, so we don't need to declare the value of the type property like previous examples.
  • The way of using the add_control method also changes. All arguments passed as class's parameter (precisely, parameters of class's constructor). Besides passing the wp_customize variable as the first parameter, perhaps you already are familiar with the latter ones including the id wptuts[color] and array of property-value pairs.
  • sanitize_hex_color_no_hash and maybe_hash_hex_color are two important sanitization functions using for Color form. The former validates that the data must be hexadecimal without a hash, which will be saved into the database. The latter ensures the output data must be validated for JavaScript use.

Check our result:


Another thing to notice is that the value of wptuts[color] is hexadecimal without a hash sign, so then when use it, remember to prepend a hash before outputting to ensuring everything works properly.

Upload Images Form

Another very useful component is the Upload Image Form, which supplies us with the ability to upload images via Ajax. We just click, choose the images, and everything will be automatically done.

Configure the setting:

$wp_customize->add_setting( 'wptuts[upload]', array(
	'type' => 'option',
) );

And the class we use is the WP_Customize_Image_Control class:

$wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'wptuts[upload]', array(
	'label'   => 'Upload',
	'section' => 'wptuts',
) ) );

The result we get will be:


Easy to upload and select and manage uploaded images:


The stored value of this setting will be the path of the selected image. You can then get the path of the image and use anywhere you want.


By this point, you’ve already learned most of the basics of the Theme Customizer’s components, how to create a new component, and customizing it in your own ways.

Again, I highly appreciate any feedbacks, comments, even unpleased things, let me know. Thanks for reading and happy coding!

Related Posts
  • Code
    Theme Development
    Custom Controls in the Theme CustomizerTheme customizer custom control 400
    In the last article, we explored the advanced controls available in the Theme Customizer, and how to implement them. We’re going to look at how to create our own custom control, allowing you to choose which Category of Posts are displayed on the home page. To get started, download version 0.6.0 of our Theme Customizer Example.Read More…
  • Code
    Validation and Exception Handling: From the UI to the BackendProcedural to oop php retina preview
    Sooner or later in your programming career you will be faced with the dilemma of validation and exception handling. This was the case with me and my team also. A couple or so years ago we reached a point when we had to take architectural actions to accommodate all the exceptional cases our quite large software project needed to handle. Below is a list of practices we came to value and apply when it comes to validation and exception handling.Read More…
  • Code
    Theme Development
    A Guide to the WordPress Theme Customizer: Advanced ControlsTheme customizer 400
    Throughout this series, we've been taking a look at the Theme Customizer, how to implement it in our themes, how to save, serialization, retrieve settings, and how to implement the options so that they automatically refresh whenever the options are updated. As we begin to wind down the series, we're going to be taking a look at the advanced controls offered by WordPress, and how to implement one of them in our theme. Then we'll be reviewing some of the resources that are available for those of you who opt to consider researching, implementing, and leveraging the Theme Customizer in your day-to-day work. But first, let's begin by taking a look at some of the controls that are offered natively with WordPress.Read More…
  • Code
    Theme Development
    A Guide to the WordPress Theme Customizer: A Methodology for Sections, Settings, and Controls – Part 2Theme customizer 400
    In the last article, we defined a simple methodology for everything that's required to establish a new Section, Settings, and Controls within the Theme Customizer. In this article, we're going to continue with doing more of the same; however, we're going to be adding new settings and controls into the existing section, but we're going to be looking at a variety of different options such as radio buttons, select boxes, and input boxes. So with that said, let's continue.Read More…
  • Code
    Theme Development
    A Guide to the WordPress Theme Customizer: Adding a New SettingTheme customizer 400
    By now, we've taken a look at what the Theme Customizer is, how it works, and the components that are unique to it. We've even discussed how options are serialized into the database so that we may retrieve them later when using our theme. To that end, it's time for us to begin doing our own work with the Theme Customizer. In this article, we're going to take a look at transports, how they work, and the difference in their two primary methods. Additionally, we're going to introduce our own control into one of WordPress' existing sections and see how it works with the various transport models.Read More…
  • Code
    Theme Development
    Digging Into the Theme Customizer: Practicing IDigging into theme customizer part 3 practicing i1
    After going through previous posts in this series, I presume that you understand the Theme Customizer components and how to add, remove, and configure them. It seems there are many things to figure out, and it will be a good exercise to put into action everything we've learned. In this post, I will cover some of the most important things about the Theme Customizer through several examples. This should result in greater understanding of the features as opposed to simply reading an article that doesn't include any code.Read More…