WP Customizer set a value via javascript (to create presets)

I am trying to find a way to send a value between 2 setting fields inside of the WordPress customizer.

My further goal is to create a preset button. I click a button inside of the customizer, and it applies pre-created values to all the other fields.

To make it easier, here is a basic example:

I have two option fields inside of the customizer. When I change the value of field 1, I would like field 2 to automatically updates to that same value as well.

theme-customizer.js

// Field 1
    wp.customize( 'field1', function( value ) {
        value.bind( function( newval ) {
                //no need to make any css changes with this field.
        } );
    } );    

// Field 2
    wp.customize( 'field2', function( value ) {
        value.bind( function( newval ) {
            $('.site-container').css('border-style', newval +'px' );
        } );
    } );    

Is there away that I could update the value of field2 when field1 is clicked?

For example:

// Field 1
    wp.customize( 'field1', function( value ) {
        value.bind( function( newval ) {
                wp.customize.value( 'field2 )(newval);//Setting the new value.
        } );
    } );    

This does work on the live preview, but the new value of field2 is not being saved when I click save. It seems the value is not being put through to PHP when using:

wp.customize.value( 'field2 )(newval);

1 Answer
1

The solution is to simply enqueue the JS value syncing snippet so that it is added in the customizer pane (customize.php) instead of the customizer preview window (on the frontend). In other words, enqueue your JS at customize_controls_enqueue_scripts instead of wp_enqueue_scripts. Here’s one snippet:

wp.customize( 'field1', 'field2', function( field1, field2 ) {
    field1.bind( function( value ) {
        field2.set( value );
    } );
} );

And here’s an even more succinct example that does the same thing:

wp.customize( 'field1', 'field2', function( field1, field2 ) {
    field2.link( field1 );
} );

Nevertheless, if you have the same value stored in multiple settings, why not just re-use the same setting in multiple places?

Leave a Comment