Skip to content

Instantly share code, notes, and snippets.

@GLWalker
Last active March 25, 2022 13:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GLWalker/9ab6dc4bc8e6940ca329c069c51a1d35 to your computer and use it in GitHub Desktop.
Save GLWalker/9ab6dc4bc8e6940ca329c069c51a1d35 to your computer and use it in GitHub Desktop.
Show or hide Wordpress Customizer controls
( function ( api ) {
'use strict';
function osq_hide_controls( id, target, option ) {
target = typeof target !== 'undefined' ? target : '';
option= typeof option !== 'undefined' ? option : '';
api( 'osq_settings[' + id + ']', function ( setting ) {
var linkSettingValueToControlActiveState;
/**
* Update a control's active state according to the setting's value.
*
* @param {api.Control} control control.
*/
linkSettingValueToControlActiveState = function ( control ) {
var visibility = function () {
if ( option === setting.get() ) {
control.container.slideDown( 180 );
} else {
control.container.slideUp( 180 );
}
};
// Set initial active state.
visibility();
// Update activate state whenever the setting is changed.
setting.bind( visibility );
};
api.control( 'osq_settings[' + target + ']', linkSettingValueToControlActiveState );
} );
}
/* usage */
osq_hide_controls( 'body_text_color', 'body_user_text_color', 'text-user' );
osq_hide_controls( 'body_background', 'body_background_color', true);
}( wp.customize ) );
@GLWalker
Copy link
Author

GLWalker commented Mar 25, 2022

Usage:
Add to your existing customizer-controls.js or otherwise enque it with the customizer.

You need to change "osq_settings[]" to match what you use in your customizer settings to pull options.
(Probably want to change the osq_ prefix on function name to match your theme as well )

osq_hide_controls( id, target, option )

id = id of the parent control in which a selected option will trigger to show or hide target option.
target = id of the control to show or hide
option = the value that will trigger the target to show or hide, can be a text option for using select options, set to true(no quotes) for checkbox option. Not tested with radio options, but it should work.

Examples:
osq_hide_controls( 'body_text_color', 'body_user_text_color', 'text-user' );

body_text_color = parent control with select menu, when option is set to text-user, the target control, body_user_text_color slides open.

osq_hide_controls( 'body_background', 'body_background_color', true);

body_background = parent control with checkbox, when option is checked, the target control, body_background_color, slides open.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment