active_callback

Can't find what you're looking for? Check the github issues or edit this page to add what's missing.

You can use the active_callback argument to define if you want to hide or display a control under conditions.

The default WordPress Customizer implementation for active_callback allows you to define a callable function or method (see the Customizer API Handbook for details).

Kirki extends the active_callback argument to allow defined field dependencies:

'active_callback' => [
	[
		'setting'  => 'checkbox_demo',
		'operator' => '==',
		'value'    => true,
	]
],

It is formatted as an array of arrays so you can add multiple dependencies.

In the example below we’re first creating a config, then a section, and finally we add 3 fields to our customizer: a checkbox, a radio and finally a text control.

The text control will only be shown if the value of the checkbox is equal to 1 and the value of the radio control is not equal to option-1.

Kirki::add_config( 'my_config' );

Kirki::add_section( 'my_section', [
	'title'    => esc_html__( 'My Section' ),
    'priority' => 10,
] );

Kirki::add_field( 'my_config', [
	'type'      => 'checkbox',
	'settings'  => 'my_checkbox',
	'label'     => esc_html__( 'My Checkbox', 'my_textdomain' ),
	'section'   => 'my_section',
	'default'   => false,
	'priority'  => 10,
] );

Kirki::add_field( 'my_config', [
	'type'      => 'radio',
	'settings'  => 'my_radio',
	'label'     => esc_html__( 'My Radio', 'my_textdomain' ),
	'section'   => 'my_section',
	'default'   => 'option-1',
	'priority'  => 20,
	'choices'   => [
		'option-1' => esc_html__( 'Option 1', 'my_textdomain' ),
		'option-2' => esc_html__( 'Option 2', 'my_textdomain' ),
		'option-3' => esc_html__( 'Option 3', 'my_textdomain' )
	]
] );

Kirki::add_field( 'my_config', [
	'type'      => 'text',
	'settings'  => 'my_setting',
	'label'     => esc_html__( 'Text Color', 'my_textdomain' ),
	'section'   => 'my_section',
	'default'   => esc_html__( 'my default text here', 'my_textdomain' ),
	'priority'  => 30,
	'active_callback'  => [
		[
			'setting'  => 'my_checkbox',
			'operator' => '===',
			'value'    => true,
		],
		[
			'setting'  => 'my_radio',
			'operator' => '!==',
			'value'    => 'option-1',
		],
	]
] );
?>

The equivalent of the above rule written as a PHP function in the callback would look like this:

'active_callback' => function() {
	$checkbox_value = get_theme_mod( 'my_checkbox', false );
	$radio_value    = get_theme_mod( 'my_radio', 'option-1' );

	if ( true === $checkbox_value && 'option-1' !== $radio_value ) {
		return true;
	}
	return false;
},

or written a lot shorter:

'active_callback' => function() {
	return true === get_theme_mod( 'my_checkbox', false ) && 'option-1' !== get_theme_mod( 'my_radio', 'option-1' );
},

The benefit however of using the field-dependencies using Kirki instead of using a PHP function is that active_callbacks are applied via JavaScript instead of PHP, so changes are instant.

Edit this page