Video Tutorial The Customize API


Today we are going to discover the WordPress Customize API which allows you to visually manage the options related to the appearance of our theme.

To use this API we will connect to the hook customize_register and use the object WP_Customize_Manager to save parameters and manage associated controls.

add_action ('customize_register', function (WP_Customize_Manager $ manager) {

    $ manager-> add_section ('montheme_apparence', (
        'title' => 'Personalization of appearance',
    ));

    $ manager-> add_setting ('header_background', (
        'default' => '# FF0000',
        'sanitize_callback' => 'sanitize_hex_color'
    ));
    $ manager-> add_control (new WP_Customize_Color_Control ($ manager, 'header_background', (
        'section' => 'montheme_apparence',
        'label' => 'Color of the header'
    )));

});

"Live" preview

By default, each modification of your WordPress setting will refresh the page to display the modifications. This can be counterproductive and ineffective for certain parameters. It is therefore possible to change the update method at the level of your parameter.

$ manager-> add_setting ('header_background', (
    'default' => '# FF0000',
    'transport' => 'postMessage',
    'sanitize_callback' => 'sanitize_hex_color'
));

WordPress will disable the refresh and instead send a message that can be captured in JavaScript to reflect the change live.

(function ($) {

    wp.customize ('header_background', function (value) {
        value.bind (function (newVal) {
            $ ('. navbar'). attr ('style', 'background:' + newVal + '! important');
        });
    });

}) (jQuery);

You can save this JavaScript thanks to the hook customize_preview_init.

add_action ('customize_preview_init', function () {
    wp_enqueue_script ('montheme_apparence', get_template_directory_uri (). '/assets/apparence.js', ('jquery', 'customize-preview'), '', true);
});

You can also check if you are in preview mode in your theme using the function is_customize_preview (). This can be useful to avoid overwriting jquery for example when saving assets:

function montheme_register_assets ()
{
    if (! is_customize_preview ()) {
        wp_deregister_script ('jquery');
        wp_register_script ('jquery', 'https://code.jquery.com/jquery-3.2.1.slim.min.js', (), false, true);
    }
}