Support » Fixing WordPress » How to diplay custom sidebar if post is from a certain category

  • Resolved Rich Owings

    (@gpsmapper)


    I want to create a custom sidebar (lets call it sidebar_2_left.php) that will be displayed if someone is viewing a single post that includes a certain category. I’ve seen ways to do this if someone is looking at the category view, but that’s not what I’m after. What’s the best way to do this? Any help would be greatly appreciated.

Viewing 6 replies - 1 through 6 (of 6 total)
  • this code snippet checks if any of the post’s category IDs is equal to a given ID (4 in the example) and then does something, if not it does something else:

    <?php
    global $post;
    $side = false;
    foreach( (get_the_category($post->ID)) as $category) {
    if ($category->cat_ID == 4) {$side = true;};
    }
    if($side) {
    //call special sidebar, for instance//;
     }
    else {
    //call normal sidebar, for instance//;
     }
    ?>

    should work inside and outside of the loop in single.php 😉

    Thread Starter Rich Owings

    (@gpsmapper)

    Thanks! I’ll give it a shot and let you know how it goes.

    Thread Starter Rich Owings

    (@gpsmapper)

    Ah, my PHP skills are in their infancy. How do I call the sidebar?

    The existing sidebar is called this way…
    <?php include(TEMPLATEPATH.”/l_sidebar.php”);?>

    looks ok.

    btw: if you google for the terms you are unsure of, (TEMPLATEPATH for instance) google will give you an almost instant answer 😉

    if you need php more often, w3c for instance has an online tutorial:
    http://www.w3schools.com/PHP/DEfaULT.asP

    Thread Starter Rich Owings

    (@gpsmapper)

    Thanks again for your help. I’m close. It works, but the layout is screwed up. Not because of this though. I think it has to do with my modified sidebar file, which includes this code copied from the original:

    <ul id="l_sidebarwidgeted">
    	<?php if ( function_exists('dynamic_sidebar') && dynamic_sidebar(1) ) : else : ?>

    I suspect that is the problem.

    Here is what I ended up with in regard to the code you supplied, FWIW:

    <?php
    global $post;
    $side = false;
    foreach( (get_the_category($post->ID)) as $category) {
    if ($category->cat_ID == 9) {$side = true;};
    }
    if($side) {
    include(TEMPLATEPATH."/l_sidebar_alt.php");
     }
    else {
    include(TEMPLATEPATH."/l_sidebar.php");
     }
    ?>
    Thread Starter Rich Owings

    (@gpsmapper)

    Hmm, well, when I pulled the suspect code the second time it worked. Not quite sure what I did different. You may have gathered that I’m using an older theme! Anyway, a bit of styling and it’s all working great. Thank you so much for your help!

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘How to diplay custom sidebar if post is from a certain category’ is closed to new replies.