has_category()
云策文档标注
概述
has_category() 函数用于检查当前文章是否属于指定的一个或多个分类。它基于文章的分类 term_ids、名称或 slugs 进行匹配,并可灵活处理参数。
关键要点
- 检查文章是否属于给定分类,参数可以是字符串、整数或数组,默认为空以检查是否有任何分类。
- 支持通过 term_ids、名称或 slugs 匹配分类,整数参数仅匹配 term_ids。
- 可选指定 $post 参数来检查特定文章,默认为当前文章。
- 返回布尔值:如果文章属于任何给定分类(或无分类指定时属于任何分类)则返回 true,否则返回 false。
- 内部调用 has_term() 函数实现,专门用于 'category' 分类法。
代码示例
// 检查当前文章是否属于特定分类
if (has_category('Category_name'))
// 检查指定文章是否属于特定分类
if (has_category('Category_name', $post->ID))
// 检查多个分类
if (has_category(array('category_name_1', 'category_name_2')))注意事项
- 在循环中使用时,无需指定 $post 参数,默认检查当前文章。
- 相关函数包括 has_term() 和 in_category(),用于更广泛的术语检查或分类检查。
- 自 WordPress 3.1.0 版本引入。
原文内容
Checks if the current post has any of given category.
Description
The given categories are checked against the post’s categories’ term_ids, names and slugs.
Categories given as integers will only be checked against the post’s categories’ term_ids.
If no categories are given, determines if post has any categories.
Parameters
$categorystring|int|arrayoptional-
The category name/term_id/slug, or an array of them to check for. Default empty.
$postint|WP_Postoptional-
Post to check. Defaults to the current post.
Default:
null
Source
function has_category( $category = '', $post = null ) {
return has_term( $category, 'category', $post );
}
Changelog
| Version | Description |
|---|---|
| 3.1.0 | Introduced. |
Skip to note 2 content
Mithun Raval
The current post has set the categories that time this function will return true.
if you want to check specific category is set for this post.
if (has_category('Category_name',$post->ID))If you want to use it in The Loop, you don’t need to specify the ID.
if (has_category('Category_name'))Check multiple category:
if(has_category(array('category_name_1', 'category_name_2')))