A Guide to the WordPress Theme Customizer: Adding a New Setting

This entry is part 4 of 4 in the series A Guide to the WordPress Theme Customizer

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.


All About Transports

Before we get into actually writing any code, one more concept with which we need to familiarize ourselves is the concept of transports. Essentially, this is how the Theme Customizer sends data to the theme in order to display the changes.

There are two ways that data can be transported:

  1. refresh – This is the default method. Using this method, when a user makes a change to a setting in the Theme Customizer, the frame displaying the theme will literally refresh before showing the change.
  2. postMessage – This method must be explicitly stated, but it provides for a much more enhanced user experience. When this method is used, an asynchronous request will be made and the appearance of the theme will be updated to reflect the user’s setting without reloading the page.

Easy enough concept, right?

Throughout this article, we’re going to implement two versions of our new Theme Customization settings. First, we’re going to work with introducing a setting that uses the refresh transport. After that, we’ll improve the setting so that it uses the postMessage transport.

At the end of the article, I’ll link to both versions of the code so that you have something that you can download and install on your local machine rather than simply having to refer to this article.

So with that said, let’s get started.


Implementing Our New Setting

In this article, we’re going to be introducing a setting that will allow users to change the color of all the anchors that exist in their theme. It’s rare that we’ll likely need to change the color of anchors universally across a site, but implementing this particular setting will teach the following:

  • How to implement a new setting into an existing section
  • How to work with the WP_Customize_Color_Control
  • How to work with the refresh transport method and how to work with the postMessage transport method

Obviously, there’s a lot of ground to cover.

Adding Our Hook

To get started, let’s add an anchor to our index.php template so that we have something to actually color. This is an easy change. Simply make sure that your index.php template contains this:

<div id="content">
	This is the content. <a href="#">This is an anchor</a> so that we can tell the Theme Customizer is working.
</div><!-- /#content -->

Next, we need to introduce a function that’s hooked into the customize_register action:

function tcx_register_theme_customizer( $wp_customize ) {
    // More to come...
}
add_action( 'customize_register', 'tcx_register_theme_customizer' );

Here, we’ve defined a function that will be used to introduce our new setting. Note that the most important thing about this function is that it accepts a single parameter – wp_customize – which is what allows us to add our our sections, settings, and controls to the Theme Customizer.

Recall in the last article, we mentioned that WordPress provides a number of sections so that we don’t have to add our own. In this case, we’ll be taking advantage of the predefined colors section.

Implementing the Setting

Within the context of the tcx_register_theme_customizer function, add the following block of code:

$wp_customize->add_setting(
	'tcx_link_color',
	array(
		'default'     => '#000000'
	)
);

This says that we’re introducing a new setting to the customizer with the ID of tcx_link_color and the default color will be black.

This will come into play when we implement the color picker. So let’s go ahead and do that now. Right after the block of code above, add the following block to your function:

$wp_customize->add_control(
	new WP_Customize_Color_Control(
		$wp_customize,
		'link_color',
		array(
			'label'      => __( 'Link Color', 'tcx' ),
			'section'    => 'colors',
			'settings'   => 'tcx_link_color'
		)
	)
);

This will introduce a color picker control into the colors section. It will add an internationalized label that reads “Link Color” and it binds itself to the tcx_link_color setting that we defined in the first block of code above.

The final version of the function should look like this:

function tcx_register_theme_customizer( $wp_customize ) {

	$wp_customize->add_setting(
		'tcx_link_color',
		array(
			'default'     => '#000000'
		)
	);

	$wp_customize->add_control(
		new WP_Customize_Color_Control(
			$wp_customize,
			'link_color',
			array(
				'label'      => __( 'Link Color', 'tcx' ),
				'section'    => 'colors',
				'settings'   => 'tcx_link_color'
			)
		)
	);

}
add_action( 'customize_register', 'tcx_register_theme_customizer' );

Demoing the Control

At this point, save your work, launch WordPress, navigate to the Theme Customizer, and you should see something like this:

The WordPress Theme Customizer - Link Color

Notice that you can expand the color picker, select colors, and generally use it as expected; however, the anchor in the content does not change at all. Next up, let’s add the following function to our functions.php file.

function tcx_customizer_css() {
	?>
	<style type="text/css">
		a { color: <?php echo get_theme_mod( 'tcx_link_color' ); ?>; }
	</style>
	<?php
}
add_action( 'wp_head', 'tcx_customizer_css' );
// TODO ?>

Obviously, this function is hooked into the wp_head action. It’s responsible for reading the value from the options table that corresponds to our new setting (identified by tcx_link_color) and then writes the value out into a style block in the header of the page.

Once done, refresh the Theme Customizer and you should notice that the changes occur whenever you select a color. You should also notice that the page flickers whenever a change is made not only to the color, but to the Title, Tagline, or Static Front Page options, as well.

Updating Our Transport

Now that we’ve got that working, we can introduce a few changes that will make the user experience a bit better as it relates to changing the theme options using the WordPress Theme Customizer.

First, we need to update our footer.php template so that it includes a call to wp_footer(). This is so that we can load up JavaScript in the footer of our theme which is necessary for the postMessage transport.

The footer should look like this:

		<div id="footer">
			&copy; <?php echo date( 'Y' ); ?> <?php bloginfo( 'title' ); ?> All Rights Reserved
		</div><!-- /#footer -->
		<?php wp_footer(); ?>
	</body>
</html>

Next, we need to update the add_setting call in functions.php so that it uses the proper transport method.

Update the code so that it looks like this:

$wp_customize->add_setting(
	'tcx_link_color',
	array(
		'default'     => '#000000',
		'transport'   => 'postMessage'
	)
);

Finally, do not remove the function tcx_customizer_css that we defined in the previous version, as it will still be required to read the value that we’re selecting for our anchors – we’re just going to be saving them asynchronously rather than on refresh.

Now create a directory in the root of your theme called js then add a theme-customizer.js file into the directory.

In this JavaScript file, we need to add the following block of code. Usually, I like to try to explain what we’re doing, but in this case, it will be easier to examine after displaying the code.

(function( $ ) {
	"use strict";

	wp.customize( 'tcx_link_color', function( value ) {
		value.bind( function( to ) {
			$( 'a' ).css( 'color', to );
		} );
	});

})( jQuery );

In this code, notice that we have access to a wp JavaScript object that offers us a customize message, much like the server-side $wp_customize->add_setting() is setup.

Next, notice that the function takes in the ID of a setting, a callback function that receives an object with the original value, and then allows us to bind another function to that object to make changes whenever that object is changed.

Still with me?

Another way of saying it is this: When the link color is changed, we’re able to make changes to the theme’s display whenever the color picker is used.

With that said, let’s revisit the functions.php file and introduce a new function so that we can properly enqueue our JavaScript file.

First, we’ll introduce a function called tcx_customizer_live_preview() and it will hook into the customize_preview_init action:

function tcx_customizer_live_preview() {
	// More to come
}
add_action( 'customize_preview_init', 'tcx_customizer_live_preview' );

Next, we’ll make a standard call to wp_enqueue_script that will bring in our theme-customizer.js file, but note that we’re passing the final argument as true so that the script is added to the footer of the document:

wp_enqueue_script(
	'tcx-theme-customizer',
	get_template_directory_uri() . '/js/theme-customizer.js',
	array( 'jquery', 'customize-preview' ),
	'0.3.0',
	true
);

The final version of the function looks like this:

function tcx_customizer_live_preview() {

	wp_enqueue_script(
		'tcx-theme-customizer',
		get_template_directory_uri() . '/js/theme-customizer.js',
		array( 'jquery', 'customize-preview' ),
		'0.3.0',
		true
	);

}
add_action( 'customize_preview_init', 'tcx_customizer_live_preview' );

Save all of your work. Assuming that you’ve done everything right, you should now be able to change the Title, Tagline, Link Color, and Static Front Page options without having to refresh the page.

A much better user experience, huh?


But There’s More to Come…

We looked at a lot in this article. So much so that the source code for this article has been released into two different downloads:

  • First, download the version that uses the refresh transport
  • Then, download the version that uses the postMessage transport

But we’re not done, yet. In the next article, we’ll take a look at how to introduce our own original section along with our own original settings and controls to round out this series.

For now, experiment with the code that we’ve made available above so that you’re ready for work in the next article!

from Wptuts+ http://feedproxy.google.com/~r/Wptuts/~3/flv7asgbMzU/

About these ads

Kommentar verfassen

Bitte logge dich mit einer dieser Methoden ein, um deinen Kommentar zu veröffentlichen:

WordPress.com-Logo

Du kommentierst mit Deinem WordPress.com-Konto. Abmelden / Ändern )

Twitter-Bild

Du kommentierst mit Deinem Twitter-Konto. Abmelden / Ändern )

Facebook-Foto

Du kommentierst mit Deinem Facebook-Konto. Abmelden / Ändern )

Google+ photo

Du kommentierst mit Deinem Google+-Konto. Abmelden / Ändern )

Verbinde mit %s