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; } }); }); }); })();
Code language: PHP (php)

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.

2 reactions on »Conditional displaying and hiding of customizer controls via JavaScript«

  1. nice tutorial, very similar to another one I found
    this one is missing an important thing.
    wp.customize.control('slug_select_control', function (control) {
    control.get() // <= this has the initial control state before any change. so you if you publish and reload everything, you wont lose the changes

    there is also an issue with :
    wp.customize.bind('ready', function () {})
    it doesn't really work as expected. it doesn't wait until all customizer objects are fully loaded. and I can prove it.
    not sure if you have any idea how to overcome this problem.

    1. Hi,

      thanks for your addition. I’m not working with the Customizer for a few years now, so I cannot help you with the problem, sorry.

Leave a Reply

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