How to create Customizer Live Preview

How to create Customizer Live Preview

Edit transport type

Default Transport type for each setting is refresh, however, if you want to create live preview customization you can change it to ‘postMessage’. Take a look at the example, we added trasport type to the color picker control.

// wpsf color picker
array(
  'name'          => 'wpsf_color_picker',
  'default'       => '#3498db',
  'transport'     => 'postMessage', // Default Transport type for each setting is refresh, however, if you want to create live preview customization you can change it to 'postMessage'. Take a look at the example, we added trasport type to the color picker control.
  'control'       => array(
    'type'        => 'wpsf_field',
    'options'     => array(
      'type'      => 'color_picker',
      'title'     => 'Color Picker Field',
    ),
  ),
),

Preparing Customizer Javascript

To handle the live preview, we need to create a Javascript file for all customizer handling. Let’s create our customizer file name wpsf-customizer.js and place it in your js theme folder.

Please notice that the control name is wrapped within _wpsf_customize_options[setting_name]

( function( $ ) {

  // Update the site title in real time...
  wp.customize( '_wpsf_customize_options[wpsf_color_picker]', function( value ) {

    value.bind( function( newval ) {
      $( 'body' ).css( {
        "background-color": newval
      });
    });

  });

})(jQuery);

Enqueue the Script

The next step is enqueuing the javascript file we have created before.

/**
 *
 * Used by hook: 'customize_preview_init'
 * @see add_action( 'customize_preview_init', $func )
 *
 */
function wpsf_customizer_live_preview() {
  wp_enqueue_script(
    'mytheme-themecustomizer', // Give the script an ID
    get_template_directory_uri().'/js/wpsf-customizer.js', // Point to file
    array( 'jquery','customize-preview' ), // Define dependencies
    '', // Define a version (optional)
    true // Put script in footer ?
  );
}
add_action( 'customize_preview_init', 'wpsf_customizer_live_preview' );

Last updated