Filter: Add/remove sidebars

Added in Marketers Delight 4.6.3, the md_filter_has_sidebar filter allows you to bypass the MD sidebar controls and conditionally add/remove the sidebar from any page.

To use this filter accurately, you must only load it on the pages you wish to manipulate and no more. Otherwise, you may encounter incorrect sidebars around your site.

By loading the filter through template_redirect, we can use a WordPress conditional tag to ensure the filter only fires on the page(s) we want it to.

When using the filter, you only need to choose the conditions and return a value of true or false to add/remove the sidebar from the given page. This would usually be done by creating a function with either return value, but we can instead use the native WordPress return functions to save us some code:

  • __return_true()
  • __return_false()

Now we can create the function that hooks into template_redirect hook, so we can edit our template, then conditionally load our filter like so:

/**
 * Manually add sidebar to different pages around the site.
 *
 * @since 1.0
 */

function md_child_theme_template_redirect() {
	// ADDS sidebar to author page
	if ( is_author() )
		add_filter( 'md_filter_has_sidebar', '__return_true' );

	// REMOVES sidebar from specific category
	if ( is_category( 'ID' ) )
		add_filter( 'md_filter_has_sidebar', '__return_false' );
}

add_action( 'template_redirect', 'md_child_theme_template_redirect' );

In the example above, we’ve ADDED the sidebar to author pages and REMOVED the sidebar from a specific post category page. You can repeat this action for as many times as you need.

Note: loading this filter without any kind of conditional tag will affect the behavior of your sidebar sitewide, so be extra careful to only use this filter in the right context.

Leave a Comment