How to set a custom Primary Sidebar for all Pages using a Page Template

In the comments section of How to set up different sidebars for archives and Pages in Genesis a user asked:

How about activating the sidebar for a particular page based upon a template? Is it too late in the build to activate the sidebar in the template itself?

We can register a custom widget area in functions.php and hook a function to genesis_after_header inside the custom Page Template to replace the default Primary Sidebar with our custom widget area in the Primary Sidebar location.

As an example let’s first register a custom widget area called “Services Sidebar” by adding the following in functions.php:

// Register services-sidebar widget area
genesis_register_widget_area(
	array(
		'id'          => 'services-sidebar',
		'name'        => __( 'Services Sidebar', 'my-theme-text-domain' ),
		'description' => __( 'Replaces the Primary Sidebar on Pages that use Services Page Template', 'my-theme-text-domain' ),
	)
);

The next step is to create the Services Page Template. Create a file named say, template_services.php having the following code:

/*
Template Name: Services
*/

add_action( 'genesis_after_header', 'sk_change_genesis_primary_sidebar' );
/**
 * Show Services sidebar in Primary Sidebar location
 */
function sk_change_genesis_primary_sidebar() {

	// remove Primary Sidebar from the Primary Sidebar area
	remove_action( 'genesis_sidebar', 'genesis_do_sidebar' );

	// show Services Sidebar in Primary Sidebar area
	add_action( 'genesis_sidebar', function() {
		dynamic_sidebar( 'services-sidebar' );
	} );

}

genesis();

That’s it. Any Page to which Services Template is applied will automatically show the widgets inside Services widget area instead of those in the Primary Sidebar.

This site uses cookies to offer you a better browsing experience. By browsing this website, you agree to our use of cookies.