最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览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.

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.
}
发布评论

评论列表(0)

  1. 暂无评论