Set a Sidebar to all posts of a Custom Post Type in Genesis

Simple Sidebars is a great plugin to use different sidebars on posts, pages, categories and tags in a Genesis theme.

You can set a certain sidebar to appear on all posts of a specific custom post type (CPT).

function themeprefix_remove_default_sidebar() {
	if ( get_post_type() == 'listing' ) { //set CPT here
		remove_action( 'genesis_sidebar', 'ss_do_sidebar' );
		remove_action( 'genesis_sidebar', 'genesis_do_sidebar' );
		add_action( 'genesis_sidebar', 'themeprefix_add_cpt_sidebar' );
 } 
}
 //Alternative Sidebar 
function themeprefix_add_cpt_sidebar() { 
dynamic_sidebar( 'sidebar-listing' );
 }
add_action( 'genesis_before_sidebar_widget_area', 'themeprefix_remove_default_sidebar' ); //sets the ball rolling

Ok so we have 2 functions and an action, the bottom action triggers it all.

The first function themeprefix_remove_sidebar() selects what we are targetting, in this example it is a custom post type that is called ‘listing‘.

Then the Simple Sidebar  and regular Genesis sidebar defaults are removed in the next 2 actions, the third action adds in the sidebar we want by calling the function below it.

In that function below – themeprefix_add_cpt_sidebar() the name/ID of the required sidebar is passed into the dynamic sidebar which will replace the sidebar for the desired content, category-sidebar in this example.

How you find the name/ID of the Simple Sidebar….

genesis-simple-sidebars

Full Gist with Comments

<?php
//do not copy the above opening php tag
/**
* Conditionally Change Sidebar in Genesis whilst using Simple Sidebars
*
* @package Genesis Simple Sidebar on Custom Post Type
* @author Neil Gee
* @link http://wpbeaches.com/set-sidebar-custom-post-type-genesis/
* @copyright (c) 2014, Neil Gee
*/
function themeprefix_remove_default_sidebar() {
if ( get_post_type() == 'listing' ) { //set CPT here
remove_action( 'genesis_sidebar', 'ss_do_sidebar' );
remove_action( 'genesis_sidebar', 'genesis_do_sidebar' );
add_action( 'genesis_sidebar', 'themeprefix_add_cpt_sidebar' );
}
}
//Alternative Sidebar
function themeprefix_add_cpt_sidebar() {
dynamic_sidebar( 'sidebar-listing' ); //add in the sidebar name
}
add_action( 'genesis_before_sidebar_widget_area', 'themeprefix_remove_default_sidebar' ); //sets the ball rolling
view raw sidebar-cpt.php hosted with ❤ by GitHub

2 Comments

  1. Hugo on November 23, 2015 at 2:01 pm

    Thanks for this useful post! But in my case I have not one, but 4 different custom sidebars to be assigned to 4 different CPTs respectively. How can I do that? Should I duplicate the function as themeprefix_remove_default_sidebar2, themeprefix_remove_default_sidebar3 etc? Or is there an easier way?

    • Neil Gee on November 24, 2015 at 8:30 am

      You could write out a bunch of conditionals if/else statements but it equally 4 different functions will suffice.

Leave a Comment





%d bloggers like this: