Sep 3, 2015
Change WordPress Customizer Control Value Programmatically
Since the WordPress Customizer is built using the Underscore.js and Backbone.js libraries, the values of all the customizer controls are not stored in the DOM, but rather in a discrete model. This means that if you use JavaScript to change the value of a control in the DOM, it will look like it has changed visually, but that value will not be saved. Underscore has two-way data binding, so if you update the value in the model (which is what WILL be saved when the user clicks Save and Publish
), it will also be updated visually in the DOM.
In order to change the value of a control, you need to bind a JavaScript function to it (see lines 5 & 6 of the code below), then use Backbone’s .set()
method to save a new value for it (see line 16).
(function ($) {
$(window).load(function () {
// When 'Use Portal Color Controls' customizer control is toggled
wp.customize("portal_color_control", function (value) {
value.bind(function (newval) {
// If toggled off, warn user that portal color settings will be deleted
if ("off" == newval) {
var confirmation = window.confirm(
"WARNING: turning this off will delete all the portal color settings. Continue?"
);
if (true == confirmation) {
// If user confirms, run code here to delete all portal color settings
} else {
// If user does not confirm, reset the customizer control to 'on'
this.set("on");
}
}
});
});
});
})(jQuery);
The example above is for on/off radio buttons. If the user clicks the off
radio button, they see a JavaScript confirm box pop up telling them that if they turn it off, some of their settings will be deleted. If they click Cancel
, the radio button control is automatically changed back to the on
value.
Debugging
To help you determine what the value of a customizer control is at a given point, you can:
- Open the Sources tab of Chrome’s dev tools.
- Find the JavaScript file.
- Click in the margin to set a breakpoint right after
value.bind()
. - Click the Scope dropdown in the right pane and view the value of this (the customizer control you bound the current function to).
- You can also set another break point after your
this.set()
code to make sure the value has been successfully changed.
Enqueue Your JS
And of course, don’t forget to enqueue your JavaScript file with code similar to this:
function km_enqueue_customizer_scripts() {
global $wp_customize;
if ( ! isset( $wp_customize ) ) {
return;
}
wp_enqueue_script( 'customizer_scripts', PLUGIN_URL . 'assets/js/customizer_scripts.js', 'jquery' );
}
add_action( 'admin_enqueue_scripts', 'km_enqueue_customizer_scripts' );