Conditional displaying and hiding of customizer controls via JavaScript

When using Partial Refresh in the customizer to reload only a part of the preview after changing a setting’s value, the active_callback for these settings is not working anymore. With active_callback you can, for example, show a control only if another control has a particular value. In that case, the conditional displaying has to be done with JavaScript.

The customizer comes with an API, which lets us activate and deactivate (show and hide) controls in a relatively straightforward way. In this tutorial, we are going to display or hide a control, depending on the value of a select list control. At first, the complete code (also available as a Gist. You can enqueue it via the customize_controls_enqueue_scripts action):

;(function () { /** * Run function when customizer is ready. */ wp.customize.bind('ready', function () { wp.customize.control('slug_select_control', function (control) { /** * Run function on setting change of control. */ control.setting.bind(function (value) { switch (value) { /** * The select was switched to the hide option. */ case 'hide': /** * Deactivate the conditional control. */ wp.customize.control('slug_conditional_control').deactivate(); break; /** * The select was switched to »show«. */ case 'show': /** * Activate the conditional control. */ wp.customize.control('slug_conditional_control').activate(); break; } }); }); }); })();

We listen to the ready event of the customizer and hook a function to the control with the ID slug_select_control, which was created with the options hide and show via $wp_customize->add_control(). With control.setting.bind, we can now call a function after the value of the control has changed.

After a change of the setting, we run a switch statement and show or hide the slug_conditional_control control with the activate() respectively deactivate() method.

Related posts

Leave a Comment

Your email address will not be published. Required fields are marked *