0

If i use has_category('dogs') on a template like index.php or archive.php or search.php and one of the posts displayed on the loop have the category dogs, will the function return true?

I know it works on single post but i need to know if it also works when on THE LOOP and any of the posts has the category.

  • 2
    No. It won’t. You will need to loop through each post and check them individually. – Jacob Peattie Jun 12 at 2:00
0

As long as has_category is used within the loop then it should work when used within index.php, archive.php, etc. You will likely run into issues if it is used outside of the loop on those templates.

  • You are right. I should have added this to my question, any way to check before? like in the header.php if any of the posts has the category? – Michael Rogers Jun 11 at 21:55
1

has_category() only tells you if a specific post has a given category (or any category, if none is provided). You can tell it which post to check by passing the post ID as the second argument. When used inside the loop however, you can omit the post ID and it will check the current post.

The problem is that if it's used outside the loop, then the 'current post' will likely be either the first or last post in the loop. Or, if there's secondary loops on the page, it could be something else entirely.

If you're on an archive page that lists multiple posts that have different categories, and you want to check if any of them have a specific category, then you're going to need to loop through them and check:

$has_category = false;

while ( have_posts() ) : the_post();
    if ( has_category( 'category' ) ) {
        $has_category = true;
    }
endif;

if ( $has_category ) {
    // At least one post has the category.
}
  • Thanks i ended up doing this using the existing loops of index, archive and search. – Michael Rogers Jun 12 at 15:45

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.