functions - Will has_category be true is used on index and one of queried posts has the category?

If i use has_category('dogs') on a template like index.php or archive.php or search.php and one of the posts d

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.

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.

Share Improve this question asked Jun 11, 2019 at 21:20 Michael RogersMichael Rogers 5498 silver badges37 bronze badges 1
  • 2 No. It won’t. You will need to loop through each post and check them individually. – Jacob Peattie Commented Jun 12, 2019 at 2:00
Add a comment  | 

2 Answers 2

Reset to default 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.

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.
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745411366a4626548.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信