Using jQuery to retrieve customizer value

I am trying to use jQuery to retrieve a theme options (customizer) value:

    $wp_customize->add_setting( 'header_fixed', array(
        'default'   => true,
    ) );
    $wp_customize->add_control( new WP_Customize_Control( $wp_customize, 'header_fixed', array(
        'label'     => __( 'Enable fixed navigation?', 'theme' ),
        'section'   => 'header_section',
        'settings'  => 'header_fixed',
        'type'      => 'checkbox',
        'priority' => 40,
    ) ) );

If the above value is true, then the header element will be fixed position. If not, it will be relative position (a class will be added, or not, with jQuery). I’m not terribly competent with jQuery, so the following is based on what comes in customizer.js, from _s:

    wp.customize( 'header_fixed', function( value ) {
    value.bind( function( to ) {
        if ( 'true' == to ) {
            $( '#header-inner' ).addClass( 'fixed' );
        }
    } );
} );

I’ve been placing this in customizer.js as doing so elsewhere results in an error: ‘wp’ is not defined.

Edit* I’m enqueuing the script as follows:

function theme_customize_preview_js() {
wp_enqueue_script( 'theme-customizer', get_template_directory_uri() .  '/js/customizer.js', array( 'customize-preview' ) );
} 
add_action( 'customize_preview_init', 'theme_customize_preview_js' );

Edit** This seems not to be quite possible at this time, so I ended up doing it with PHP:

<?php if ( '' != get_theme_mod( 'header_fixed') ) echo 'fixed'; ?>

Thanks!

1 Answer
1

Use that JQuery code from your question in customizer preview for real time update. Your transport should be set to ‘postMessage’. In your website you can add body class in function.php:

function theme_prefix_body_class( $classes ) {

    if ( get_theme_mod('header_fixed', 0 ) == true  ) {

        $classes[] = 'fixed-header';
    }

    return $classes;
}
add_filter( 'body_class', 'theme_prefix_body_class' ); 

Leave a Comment