admin管理员组文章数量:1425915
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
2 Answers
Reset to default 0As 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.
}
本文标签: functionsWill hascategory be true is used on index and one of queried posts has the category
版权声明:本文标题:functions - Will has_category be true is used on index and one of queried posts has the category? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745411365a2657484.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论