WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] How to diplay custom sidebar if post is from a certain category (7 posts)

  1. Rich Owings
    Member
    Posted 4 years ago #

    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.

  2. alchymyth
    The Sweeper & Moderator
    Posted 4 years ago #

    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 ;-)

  3. Rich Owings
    Member
    Posted 4 years ago #

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

  4. Rich Owings
    Member
    Posted 4 years ago #

    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");?>

  5. alchymyth
    The Sweeper & Moderator
    Posted 4 years ago #

    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

  6. Rich Owings
    Member
    Posted 4 years ago #

    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");
     }
    ?>
  7. Rich Owings
    Member
    Posted 4 years ago #

    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!

Topic Closed

This topic has been closed to new replies.

About this Topic