Hostingheaderbarlogoj
Join InMotion Hosting for $3.49/mo & get a year on Tuts+ FREE (worth $180). Start today.
Advertisement

Digging Into the Theme Customizer: Practicing II

by
Gift

Want a free year on Tuts+ (worth $180)? Start an InMotion Hosting plan for $3.49/mo.

This post is part of a series called Digging Into the Theme Customizer.
Digging Into the Theme Customizer: Practicing I

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!

Advertisement