Last active
December 28, 2022 23:29
-
-
Save florianbrinkmann/e44e62eb77333e8e080d7ac605b91da0 to your computer and use it in GitHub Desktop.
Show or hide WordPress customizer control on change of another control. https://florianbrinkmann.com/en/3783/conditional-displaying-and-hiding-of-customizer-controls-via-javascript/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;(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; | |
} | |
}); | |
}); | |
}); | |
})(); |
Works once, then, when Customizer get refresh, the control appear again. Don't know how to solve this.
Found the solution, instead of use the method deactivate and activate, use toggle like this:
wp.customize.control('my_control', function (control) {
const toggleControl = (value) => {
if (condition) {
wp.customize.control('control_to_hide').toggle(true);
} else {
wp.customize.control('control_to_hide').toggle(false);
}
};
toggleControl(control.setting.get());
control.setting.bind(toggleControl);
});
Found the solution, instead of use the method deactivate and activate, use toggle like this:
wp.customize.control('my_control', function (control) { const toggleControl = (value) => { if (condition) { wp.customize.control('control_to_hide').toggle(true); } else { wp.customize.control('control_to_hide').toggle(false); } }; toggleControl(control.setting.get()); control.setting.bind(toggleControl); });
condition undefined?
@lwxbr Cheers that worked!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@CA-Irag and others who have faced the same problem is because of the lack of server side
active_callback
for the control. This jQuery only makes active/inactive on real time front end HTML. You also need to setup aactive_callback
for the desired control.Here is more details on it - https://make.xwp.co/2016/07/24/dependently-contextual-customizer-controls/