0

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();
    }
?>
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 Dec 23 '18 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 Dec 23 '18 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 Dec 23 '18 at 5:11
  • 1
    in_category() worked! That one letter change just salvaged my weekend. Sally CJ, I shall also worship you. – marilynn Dec 23 '18 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 Dec 23 '18 at 6:29
0

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

3
  • that was me struggling to post the updated code. (It's my first day using the forum.) Is there an advantage to using has_category() vs in_category()? – marilynn Dec 23 '18 at 6:34
  • They both do the same thing. Not sure if there's any difference performance wise. in_category is the older version of has_category, it is still supported though and it uses has_category behind the scenes. – Sheedo Dec 23 '18 at 6:52
  • @marilynn, in_category() and has_category() both use (or are wrappers for) has_term(). But unlike has_category(), in_category() requires the category name/ID/slug (or array of said) which is the first parameter, be specified at all times - if has_category() is called without any parameters, then you're basically checking if the current post has any categories. So if you call in_category() without the first parameter, then false is returned all the times, despite the post has categories. Hope that helps. :) – Sally CJ Dec 23 '18 at 7:34
0

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

?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.