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?

2 Answers
2

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 have sidebar-2 as the content sidebar.

//Register the alternative sidebar
register_sidebar( array(
    'name'         => __( 'Custom Sidebar' ),
    'id'           => 'cpt-sidebar',
    'description'  => __( 'Sidebar for showing cpt-specific content.' ),
    'before_title' => '<h1 class="widget-title">',
    'after_title'  => '</h1>', 
    'before_widget' => '<aside id="%1$s" class="widget %2$s">',
    'after_widget'  => '</aside>',
    ) );

add_action('get_sidebar','change_cpt_sidebar');
function change_cpt_sidebar($sidebar) {

    if ( (is_post_type_archive('my_cpt') || is_singular('my_cpt') || is_tax('cpt_tax')) && $sidebar == 'content') { // Check if we're on a CPT page
        unregister_sidebar( 'sidebar-2' );
        ?>
        <div id="content-sidebar" class="content-sidebar widget-area" role="complementary">
            <?php
        dynamic_sidebar( 'cpt-sidebar' );
        ?>
    </div>
    <?php
     }
}

Leave a Reply

Your email address will not be published. Required fields are marked *