How to Implement the WordPress Theme Customizer

Posted OnMay 4, 2015     CategoryDevelopment     CommentsNo comment

Since the release of WordPress 3.4, the Theme Customization API has been available, which allows developers to easily add theme customization options. A user can open the customizer via WordPress Dashboard » Appearance » Customize, and make changes that are visible in real time. As such, when you’re building a theme, you should always include customization functionality.

In this article we’re going to see how to implement the Theme Customization API in a WordPress theme.

Registering with the Theme Customization API

To keep our code clean I am going to create a child theme and then use the theme customization option within it. To create a child theme create a new folder, we’re naming ours themecustomizerchild. Then in the newly created folder, create a new file called style.css and add the following code

/*
Theme Name:     Twenty twelve child to use theme customiser
Theme URI:      
Description:    Child theme to demo use theme customiser
Author:         Abbas S
Template:       twentytwelve
Version:        1.0
*/

@import url("../twentytwelve/style.css");

This will create a child theme of TwentyTwelve (you can create the child theme from any base theme) and you should be able to see your child theme in the options as shown below. Once you’ve made it to here, you can activate your child theme.

Child Theme Registered

Once we have activated the child theme we will register the customize_register hook of WordPress which is used to manipulate the theme customization screen. To do that create a functions.php file in your child theme with the following code

<?php
function childheme_customize_register( $wp_customize ) {
    //All our sections, settings, and controls will be added here
}
add_action( 'customize_register', 'childheme_customize_register' );

Here we register our function childheme_customize_register for the hook customize_register which passes an object of the WP_Customize_Manager class which can be used to add customization options for your theme.

Defining Section, Setting, and Controls

Once we’ve registered our function to the customize_register WordPress hook, we can start creating our customization settings. First, we’ll create a separate section to hold our settings. Its always a good practice to club similar settings or settings in the same logical group under one section so that it is easy for someone to set them from the theme customizer page.

Then, we can add one or more settings to that section. Each setting is one individual value that the user will be able to set. With every setting you will have to add a visual control like text or checkbox etc which will be displayed to take the setting from the admin.
To add the settings lets update the code of childheme_customize_register as shown below

function childheme_customize_register( $wp_customize ) {
    
    //Adding a section
    $wp_customize->add_section(
                        'footer_setting_section',
                        array(
                            'title' => 'Footer Settings',
                            'description' => 'This section club the setting for the fotter of the theme.',
                            'priority' => 9999,
                        )
    );
    
    //Add a setting
    $wp_customize->add_setting(
                    'show_footer_text'
    );
    
    
    //Add control
    $wp_customize->add_control(
                    'show_footer_text',
                    array(
                        'type' => 'checkbox',
                        'label' => 'Show footer text',
                        'section' => 'footer_setting_section',
                    )
    );
    
    //Add a setting
    $wp_customize->add_setting(
                    'footer_text_textbox',
                    array(
                         'default' => 'Footer text goes here',
                    )
    );
    
    //Add control
     $wp_customize->add_control(
                    'footer_text_textbox',
                    array(
                        'label' => 'Footer text',
                        'section' => 'footer_setting_section',
                        'type' => 'text',
                    )
    );
}

In the above code we created one section which is done using the function add_section which takes two parameters, an unique id for the section, and an array of arguments like the title, description and priority (I have given a higher number in priority so that the section displays at the end). Then we have added two settings, show_footer_text and footer_text_textbox which will hold the values whether the footer text should be shown or not, and what the footer text should be, by using the function add_setting. Then I will associate a check box control to show_footer_text and text control to footer_text_textbox using the add_control function.

Once we have added this code we should be able to see our setting in theme customizer as shown below

Area for Footer Text

Outputting Customizations in Our Theme

With these functions created, we don’t have to worry about saving the various settings, that is now up to WordPress to manage. But, what we do need to do, is instruct WordPress where to put the retrieved values in our theme.
To do this, we need to create footer.php in our Child Theme, and add a little code to it. Remember: we’re using a theme based on TwentyTwelve, so for this we’re copying the existing footer.php and then just adding what we need to, you will likely do the same based on your approach.

</div><!-- #main .wrapper -->
	<footer id="colophon" role="contentinfo">
		<div class="site-info">
			<?php if( get_theme_mod( 'show_footer_text' ) == '1' ){
			    echo get_theme_mod( 'footer_text_textbox', 'No footer text added as yet.' );
			} 
			?>
		</div><!-- .site-info -->
	</footer><!-- #colophon -->
</div><!-- #page -->

<?php wp_footer(); ?>
</body>
</html>

In the above code we use the WordPress function get_theme_mod to get the values of the settings. The function get_theme_mod will return an empty value if the checkbox is not set, but will return ‘1’ if it is set. So we are first checking if the check box is checked, and in that case we get the value of the footer_text_textbox setting and display in the footer.

Now if we select the checkbox in the setting and add a footer message and save it as shown below

Customizing our footer text

You will be able to see the footer message on the site as shown below

Viewing the output of our footer text

Live Preview

The WordPress Theme Customizer allows you to have live previews of changes, so the user can see the changes as they are made. To do this you have to use some extra JavaScript code to make it work.

The first thing we need to do is to add the transport parameter as postMessage while adding the setting as shown below

//Add a setting
    $wp_customize->add_setting(
                    'footer_text_textbox',
                    array(
                         'default' => 'Footer text goes here',
                         'transport'   => 'postMessage'
                    )
    );

Then we need to add a JavaScript file in our child theme called child-theme-customizer.js with the following code

( function( $ ) {
	wp.customize( 'footer_text_textbox', function( value ) {
		value.bind( function( to ) {
			$( '.site-info' ).text( to );
		} );
	} );
})( jQuery );

In the above code we are just changing the text of .site-info with the new text which we get.

Now we just need to enqueue this script. To do that, add the following code to functions.php which hooks into the customize_preview_init hook of WordPress and enqueue our JavaScript file.

function childtheme_customizer_live_preview() {
    wp_enqueue_script(
        'child-themecustomizer',			
        get_stylesheet_directory_uri().'/child-theme-customizer.js',
        array( 'jquery','customize-preview' ),	
        '1.0',						
        true						
    );
}
add_action( 'customize_preview_init', 'childtheme_customizer_live_preview' );

Note: We have to use the WordPress function get_stylesheet_directory_uri to get the URI of child theme

Once we have done it the value will reflect as and when we are typing in the setting box as shown below.

Live preview of customizer changes now working

Conclusion

As you can see, the Theme Customization API is the best, and standard, way of adding theme options for users. It can help remove or reduce the options page that a lot of themes tend to come with at the moment. WordPress does a great job of abstracting features like this, making them super easy for developers to implement.

Leave a Reply

Your email address will not be published. Required fields are marked *

Send this to friend