I want to replace the sidebar-2
in the twentyforteen theme with a custom sidebar based on a conditional statement for CPT. So if the page is showing a certain custom post type then show my custom sidebar, else just show the default sidebar.
I want to do this without changing the theme or using a child theme (i.e. purely from a plugin).
Here is what I have so far:
register_sidebar( array(
'name' => __( 'Custom Sidebar' ),
'id' => 'custom-sidebar',
'description' => __( 'My Custom Sidebar' ),
) );
add_action('get_header','change_dd_sidebar');
function change_dd_sidebar() {
if ( is_singular('my_cpt')) { // Check if we're on a single post for my CPT called "ips_due_diligence". Need another check for index pages too.
unregister_sidebar( 'sidebar-2' ); //remove the default right sidebar
dynamic_sidebar( 'custom-sidebar' ); //this doesn't replace the right sidebar - the content appears at the top of the page - no good...
}
}
Is there a way to hook into the call for sidebar-2
and replace it with my own?
I have figured this out. The trick is to use the
get_sidebar
hook and run some conditionals to check if we’re on a CPT page (archive or singular or cpt taxonomy archive) and if the sidebar we’ve hooked into is the one we want to replace ($sidebar == 'content'
).If these conditionals are met we unregister
sidebar-2
and add our own sidebar. This probably won’t work with a theme that doesn’t havesidebar-2
as thecontent
sidebar.I wouldn’t use
unregister_sidebar
I would copy over the sidebar-content.php file to a plugin and add conditionals to the default sidebar-2 as well as add a new sidebar-4 in that file with the conditional for it.
You would also need to add a functions.php or plugin.php file with the code to register your new sidebar-4 very much like what you would do with a child theme.
You could also create a single-cpt.php file and add the sidebar-4 in there.