categories - Sidebar by Category Conditional Statement not functioning

admin2025-06-05  3

I have two categories for my posts, "event" and "long-term-leasing." I have sidebar-events.php and sidebar-long-term.php. I wrote a conditional statement in single.php, but when I view a post it only shows me the generic sidebar. I did a copy/paste of the categories to avoid typos. Where is my mistake?

    <?php
    if (is_category("event")) {
        get_sidebar('events');
    } elseif (is_category('long-term-leasing')) {
        get_sidebar('long-term');
    } else {
        get_sidebar();
    }
?>

I have two categories for my posts, "event" and "long-term-leasing." I have sidebar-events.php and sidebar-long-term.php. I wrote a conditional statement in single.php, but when I view a post it only shows me the generic sidebar. I did a copy/paste of the categories to avoid typos. Where is my mistake?

    <?php
    if (is_category("event")) {
        get_sidebar('events');
    } elseif (is_category('long-term-leasing')) {
        get_sidebar('long-term');
    } else {
        get_sidebar();
    }
?>
Share Improve this question asked Dec 22, 2018 at 23:50 marilynnmarilynn 51 bronze badge 6
  • Are you sure they are terms in the category taxonomy? If so, maybe you need to reset the main WordPress query - add wp_reset_query(); before the if block starts. – Sally CJ Commented Dec 23, 2018 at 0:14
  • They are categories. I cut and pasted from the category dashboard to ensure accuracy. I tried your suggestion, but sadly there was no change. – marilynn Commented Dec 23, 2018 at 3:30
  • Ah, "in single.php". That's why the is_category() fails. Try in_category(). But I assume the post would only be in one of those categories? – Sally CJ Commented Dec 23, 2018 at 5:11
  • 1 in_category() worked! That one letter change just salvaged my weekend. Sally CJ, I shall also worship you. – marilynn Commented Dec 23, 2018 at 6:14
  • I would like to post the corrected code here, but I can't figure out how to properly wrap the code. – marilynn Commented Dec 23, 2018 at 6:29
 |  Show 1 more comment

2 Answers 2

Reset to default 0

Try has_category, instead; is_category is used for archive pages, not single posts.

For all who are struggling, here is what worked for me:

<?php
if (in_category("event")) {
    get_sidebar('events');
} elseif (in_category('long-term-leasing')) {
    get_sidebar('long-term');
} else {
    get_sidebar();
}

?>

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749074279a316132.html

最新回复(0)