Using active callbacks in the Customizer

One thing I haven’t seen many themes use is active callbacks to their advantage. What are they and how can they used? It’s actually quite simple and there are two methods that the customizer has available. The first one is when you first create the section, panel, or control.

$wp_customize->add_section( 'meta-slider-section',
	array(
		'title' => __( 'Meta Slider Section', 'jc-domain' ),
		'description' => __( 'Input the ID of a slider and it will display on this section of the theme', 'jc-domain' ),
		'active_callback' => 'is_meta_active',
	)
);

Great! We have a section but how do make sure that it will only be seen when the plugin is active? The 'active_callback' function will be used. In that function we can setup our logic so that the section will only show if the meta slider plugin is active.

function is_meta_active(){
	// Check for the slider plugin class
	if( !class_exists( 'MetaSliderPlugin' ) ) {
	// If it doesn't exist it won't show the section/panel/control
		return false;
	} else {
	// If it does, we do show it
		return true;
	}
}

Fairly neat right? What’s really awesome is that you can do this with controls as well. Let’s say we want a control to only show with a specific page template. You can use the callback function to look something like:

function is_certain_page_template() {
	// Get the page's template
	$template = get_post_meta( get_the_ID(), '_wp_page_template', true );
	$is_template = preg_match( '%fullwidth.php%', $template );	if ( $is_template == 0 ) {
		return false;
	} else {
		return true;
	}
}

Now, I mentioned there are two methods of using active callbacks. The second method is by using an extending class. Let’s say we have a custom control class that we only want to show when an option is selected.

Now, I mentioned there are two methods of using active callbacks. The second method is by using an extending class. Let’s say we have a custom control class that we only want to show when an option is selected.

if ( class_exists( 'WP_Customize_Manager' ) ):
class JC_Manic_Control extends WP_Customize_Control {
	function active_callback(){
		// This is the function that will house the logic so our control
		// shows only when we need it to. This will override the
		// WP_Customize_Control's active_callback function.
		return false;
	}
	function render_content(){
		// other code goes here, keeping it simple for demonstration purposes.
	}
}
endif;

Pretty darn cool if you ask me. Now, with those two methods you can create a much better experience with your theme options and customizations. So, go on and explore and experiment with active callbacks. Add it to your repertoire of theme tools and WordPress knowledge!

By Jose

Born in El Salvador. Loves to read, write, draw, paint, build, test, typography, hike, photography, art, design, sewing, and many other things.