Where do posts get the sidebar from?

I’m trying to add an if statement on the sidebars that are displays in POSTS. I want posts to show a specific sidebar if it’s in category x and display a different sidebar if it’s not in category x.

To do this, i’m trying to use the following code:

Read More
<?php if ( in_category( 'featured-listing' ) || ( in_category( 'listing-post' ) )) { ?>
    <?php get_sidebar(); ?>
<?php } else { ?>
   <?php get_sidebar2(); ?>
<?php } ?>

I’ve tried editing both the single.php and page.php to no avail. I thought maybe that since i removed the get_sidebar from my child theme that WordPress was falling back to the Twentytwelve sidebar, but after trying a few things out it seems this isn’t the case.

So – the summarize; i’ve tried editing both single.php and page.php to try and display different sidebars based on the category that the post is assigned to.

Thanks in advance.

Related posts

2 comments

  1. get_sidebar() accepts a parameter $name. Then will look for a file sidebar-{$name}.php.

    So what you can do is:

    get_sidebar( get_post_type() ); // search for sidebar-post.php or sidebar-page.php
    

    or:

    if ( in_category( array( 'featured-listing', 'listing-post' ) ) )
        get_sidebar( 'listing' ); // sidebar-listing.php
    else
       get_sidebar();
    
  2. As you want to define separate sidebar for :

    1.post

    2.and page

    3.in post for category

    Place below code in your sidebar.php

    <?php
    if( 'post' == get_post_type()){
        $categories = get_the_category();
        foreach( $categories as $category ){
            $sidebar_template[]='sidebar-'.$category->slug.'.php';
        }
        //search for template for category
        $cat_template = pathinfo( locate_template( $sidebar_template ) );
        if( !empty( $cat_template )){
            $cat_template_name=explode( '-', $cat_template['filename'] , 2);
            get_sidebar( $cat_template_name[1] );
        }
        else{
            get_sidebar( 'post' );
        }
    
    }else{
        get_sidebar('page');
    }
    ?>
    

    and create

    1.sidebar-page.php for page

    2.sidebar-post.php for post

    3.sidebar-category_slug.php for post category

    what code does:

    1.If get_post_type is equal to post then , I retrieve all categories for current post and test is their any sidebar template for category it.if yes then sidebar for category will call ( sidebar-category_slug.php )else sidebar for post will call ( sidebar-post.php ).

    2.If get_post_type is equal to page then sidebar for page will call ( sidebar-page.php ).

    Note: code drived only for assuming current condition.We can modify it for different levels for example if we want to separate sidebar template for sub category.

Comments are closed.