Digging Into the Theme Customizer: Practicing II

Digging Into the Theme Customizer: Practicing II

Tutorial Details
  • Program: Wordpress 3.4+
  • Topic: Theme Customizer
  • Difficulty: Beginner
This entry is part 4 of 4 in the series Digging Into the Theme Customizer

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.


Sanitization

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' => 'mail@mail.com',
		'type' => 'option',
		'sanitize_callback' => 'check_email'
	) );
digging-into-theme-customizer-part-4-practicing-1

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.


Transport

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:

digging-into-theme-customizer-part-4-practicing-2

Output:

digging-into-theme-customizer-part-4-practicing-3

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:

digging-into-theme-customizer-part-4-practicing-4

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:

digging-into-theme-customizer-part-4-practicing-5

Easy to upload and select and manage uploaded images:

digging-into-theme-customizer-part-4-practicing-6

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.


Conclusion

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!


Other parts in this series:Digging Into the Theme Customizer: Practicing I
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Castle

    Another great article.

    I just hope that the next one you can include examples of WP_Customize_Background_Image_Control

    • Lee
      Author

      Hi Castle,

      In previous post, you suggested me supplying an example of WP_Customize_Background_Image_Control (WCBIC), it’s a shame that I’ve misread it and just thought of it as WP_Customize_Image_Control (WCIC). In fact, however, WCBIC class is a child class of WCIC (their names imply that too) and it is more specialized and only used for a setting named “background_image” (this setting is used for customizing site’s background). So, if you want to use an Upload Image Form, I recommend you to use WCIC as I did in this post. Moreover, Background feature was implemented by default in all theme, you don’t need to use WCBIC, I’m not sure whether or not you have another purpose (if so, tell me know). Whenever got problems of anything, feel free to tell me know. Thank you, Castle.

      • Castle

        Hi Lee,

        I was thinking that WCBIC can be handy if you want to allow the user to upload several background images. For example, you can give the user the possibility to use background images for the HTML element, BODY element.. and so on. Would be nice if you could show an example of WCBIC.

        • Lee
          Author

          Hey Castle, I see. You could easily do that with WCIC. I’ll use the example in the end of this post. To get the value of “wptuts[upload]” setting, you can do this (add this code in functions.php):

          function set_background_example() {
          $wptuts = get_option('wptuts');
          $url = $wptuts['upload'];
          ?>

          /* The HTML element you want, assuming the id #element_you_want */
          #element_you_want {
          background-image: url('');
          }

          <?php
          }
          add_action( 'wp_head', 'set_background_example' ); // Embed that stylesheet in the site's head section.

          Then, that HTML element will be set the background image. Hopefully you understand this example.

          • Castle

            Hi Lee, thanks for the code. I thought in using WCIC, but problem with WCIC is that you don’t have the background parameters(position, repeat and attachment) that WCBIC offers you.

          • Lee
            Author

            Hi Castle. You could add other new settings for each of those. Way back to previous post, you can see some examples of type of settings such as radio, select list. There’re basically three steps: add a new setting, add a control for it, then get the value of it for using (like the comment above). If you follow previous posts carefully, I think you can do it :).

  • http://www.facebook.com/rich.rich.399 Rich Isn’t Rich

    Totally agree with the previous comment

  • Moisei

    If i have several elements of the same type, lets say text inputs, They all are getting the same type of value: just text. How should i make sanitize functions in this case? Every element should get it’s own repeated function or should i make one function and call it in every element in this line: ‘sanitize_callback’ => ‘function_name’?

    • Lee
      Author

      Hi Moisei, if your settings have same kind of validation, then you should make one function for them for optimizing code snippets. Of course, there will situations that you can’t do that (some settings are more complicated), then you have to make an individually function for each of them.

  • jasmine

    oh, nice i found here too from amdhas..he has good talent.

    http://amdhas.com/blog/typography-customizer-in-wordpress-theme

  • http://www.affordable-seo-package.tweet-me.net/ seoKamrul

    Hi, I was just wondering if the theme customizer api has its won way to show error messages. Suppose user inputted email address does not pass through the validation process. This must be notified to user. How would you do that?

    • Lee
      Author

      Hi seoKamrul, as I see, Theme Customizer currently has no way to display error messages to user. Maybe there will a tricky way to do that though. Let me try it out…

  • http://www.facebook.com/numediaweb Abdessamad Idrissi

    Thanks for this great article.

    Do you know if it is possible to have a date-picker controller?

    • Lee
      Author

      Thanks Abdessamad. The Datepicker JqueryUI widget would be a candidate :). You could take a look at the overview post of this series where I showed how to embed JS code in Theme Customizer page. If you still find it difficult to figure out, just tell me, I’ll give it a try.

  • http://www.facebook.com/numediaweb Abdessamad Idrissi

    .. and also how to remove the existing items; like site title and tagline, navigation..etc.

    tahnks again :)

    • http://www.facebook.com/numediaweb Abdessamad Idrissi

      I figured how to remove pre existing items;

      // Remove non dynamic settings

      $wp_customize->remove_section(‘title_tagline’);

      $wp_customize->remove_section(‘nav’);

      $wp_customize->remove_section(‘static_front_page’);

  • steve

    Glad i found this, makes more sense than a custom settings page.

    One question though, is it possible to sore an array rather than single value?

    For example, in your upload image example, the currently selected image is the option value. I would like to be able to retrieve all images uploaded in an array, say for a slideshow feature.

  • Nirjhar Lo

    Hi Lee

    It was great article. I have one question though.
    I was using WP_Customize_Image_Control to upload images in my theme customizer. The form works fine. But I am unable to fetch the url by using:

    from the control defined under “the_settings_name”. As the key ‘type’ is set to ‘option’, in settings definition I used ‘get_option()’ Searched a lot but found no information. Can you say how to fetch the path of the selected image.

    • Nirjhar Lo

      I have found out the solution. In last paragraph you have added WP_Customize_Image_Control with the same name as targeted settings name ‘wptuts[upload]‘
      For using it give a unique control name and mention settings name as following example:

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

      ) ) );

      Here is the link I found the solution. People having same problem may get benifit as there is not enough docs regarding customization API in codex till date:
      http://themes.svn.wordpress.org/portfolio-press/1.5/extensions/options-functions.php

      • Lee
        Author

        Right, Nirjhar. The id value of the Control doesn’t matter. We could use it to tell the Control which setting it will control or simply give it another value and define the setting’s id in the settings property in subsequently array option.

  • Carl Hughes

    How do I ‘echo’ out the colour form to my header.php?

    • Nirjhar Lo

      Example Code (please notice the change of name in control name and in addition of ‘settings’ element in control array elements):

      $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',
      ) );
      $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'a_name', array(
      'label' => 'Color',
      'section' => 'wptuts',
      'settings' => 'wptuts[color]',
      ) ) );

      Then just call

      echo get_option( 'wptuts[color]' );

      in live header css.

      That will do.

      • Lee
        Author

        Thanks Nirjhar. It’s a tiny mistake (I thought) when you get directly the color value in the wptuts setting option. I think we should use like this:


        $wptuts = get_option( 'wptuts' );
        // Then reference to the color value
        // Output it or whatever
        $color = $wptuts['color'];

  • Carl Hughes

    Same with the ‘Upload images form’

    • Nirjhar Lo

      Same as color control. Rectify your code accordingly. Please use pre defined ‘settings’ name in WP_Customize_Image_Control array. And use a different name for your control other than your settings name.
      Then use get_option( ‘your_settings_name’ ) to retrive the image url.
      Hope that helps.

  • 忠沅 李

    Though in a hurry. Thanks.
    I have written a flex, for uploading and selecting posts and attachments.
    It’s a need to develop a new extended component. I encountered problem when integreting it to WP Customizer Environment. So you help me a lot.
    I watched the customize-controls.js, it makes me dizzy. I know little about js.
    Everything will be ok if i have a understand towards how WP_Customize_Control class work, isn’t it?

    • Lee
      Author

      Agree with you that read the JS source is kind of complex. :D Honestly, I mainly focus on 4 main PHP file of WP Theme Customizer. It’s useful if you understand how the Control works.

      • 忠沅 李

        Thanks a lot. I have solved the problem via some ‘abnormal’ approaches, by changing some codes of customize-controls.js, to support my new control. I may try to understand it in the future. Realy thanks!^_^