Theme customizer live preview with js in wordpress.
For customizer live preview we need to add hook in wp_head & customize_preview_init function. We have to include our customize style & customize preview js via add_action in fuctions.php . You can check the following example:
//theme customizer styles
function my_customizer_styles(){?>
<style type="text/css">
footer .site-footer-inner .bottom-footer{
background-color: <?php echo get_theme_mod('theme_footer_bg'); ?>;
}
</style>
<?php
}
add_action( 'wp_head', 'theme_customizer_styles', 99 );
// customizer live preview js
add_action( 'customize_preview_init', 'theme_customize_preview_js', 999, 1 );
function dws_customize_preview_js() {
wp_enqueue_script( 'dws-customizer-js', get_stylesheet_directory_uri() . '/inc/customizer/customizer.js', array( 'customize-preview' ) );
}
// Add this code in customizer.js
(function( $ ) {
wp.customize('theme_footer_bg', function(value) {
value.bind(function(to) {
$('footer .site-footer-inner .bottom-footer').css('background-color', to);
});
});
})( jQuery );
Finally you have to add ‘transport’ => ‘postMessage’ in your registered theme_customizer add_setting option.
Example:
$wp_customize->add_setting( ‘theme_footer_bg’, array(‘transport’ => ‘postMessage’,));
Now your theme customizer chagnes will preview live without page loading.