Using WordPress ‘customize_preview_init’ PHP action

The customize_preview_init WordPress PHP action fires once the Customizer preview has initialized and JavaScript settings have been printed.

Usage

add_action('customize_preview_init', 'your_custom_function');
function your_custom_function() {
    // your custom code here
}

Parameters

  • $manager (WP_Customize_Manager) – WP_Customize_Manager instance.

More information

See WordPress Developer Resources: customize_preview_init

Examples

Enqueue a custom script for the Customizer live preview

Enqueue a custom script to control live previews in the Theme Customizer.

add_action('customize_preview_init', 'my_theme_customizer_enqueue_script');
function my_theme_customizer_enqueue_script() {
    wp_enqueue_script('my-theme-customizer', get_template_directory_uri() . '/js/theme-customizer.js', array('jquery', 'customize-preview'), '1.0', true);
}

Change the Customizer’s loading message

Customize the loading message shown when the Customizer preview initializes.

add_action('customize_preview_init', 'change_customizer_loading_message');
function change_customizer_loading_message() {
    wp_add_inline_script('customize-preview', "jQuery(document).ready(function() {jQuery('#customize-preview').html('<h3>Loading your custom preview...</h3>');});");
}

Include Google Fonts in Customizer preview

Include Google Fonts in the Customizer preview, allowing you to see font changes live.

add_action('customize_preview_init', 'include_google_fonts_in_customizer');
function include_google_fonts_in_customizer() {
    wp_enqueue_style('google-fonts', 'https://fonts.googleapis.com/css?family=Roboto&display=swap', array(), null);
}

Customize the Customizer’s CSS

Add custom CSS to the Customizer preview for a more consistent look with your theme.

add_action('customize_preview_init', 'add_custom_css_to_customizer');
function add_custom_css_to_customizer() {
    wp_add_inline_style('customize-preview', ".customize-control-title {color: #333; font-weight: bold;}");
}

Enqueue a custom script and style for the Customizer live preview

Enqueue custom scripts and styles specifically for the Customizer live preview, without affecting the live site.

add_action('customize_preview_init', 'enqueue_customizer_assets');
function enqueue_customizer_assets() {
    wp_enqueue_script('customizer-js', get_template_directory_uri() . '/js/customizer.js', array('jquery', 'customize-preview'), '1.0', true);
    wp_enqueue_style('customizer-css', get_template_directory_uri() . '/css/customizer.css', array(), '1.0');
}