is_category()
云策文档标注
概述
is_category() 是 WordPress 的条件标签函数,用于判断当前查询是否为现有分类存档页面。它可接受可选参数来检查特定分类。
关键要点
- 函数返回布尔值,指示查询是否为分类存档页面
- 可选参数 $category 可以是分类 ID、名称、别名或它们的数组,用于精确匹配
- 在查询运行前使用会返回 false,并触发 _doing_it_wrong() 警告
- 内部调用 WP_Query::is_category() 实现功能
- 适用于主题开发中的条件判断,如模板加载或内容显示
代码示例
is_category();
// 当任何分类存档页面显示时返回 true
is_category( '9' );
// 当分类 ID 为 9 的存档页面显示时返回 true
is_category( 'Stinky Cheeses' );
// 当分类名称为 "Stinky Cheeses" 的存档页面显示时返回 true
is_category( 'blue-cheese' );
// 当分类别名为 "blue-cheese" 的存档页面显示时返回 true
is_category( array( 9, 'blue-cheese', 'Stinky Cheeses' ) );
// 当分类为 ID 9、别名 "blue-cheese" 或名称 "Stinky Cheeses" 之一时返回 true注意事项
- 对于自定义分类法,应使用 is_tax() 函数
- 相关函数包括 is_archive(),用于更通用的存档页面判断
- 函数自 WordPress 1.5.0 版本引入,数组参数支持从 2.5 版本开始
原文内容
Determines whether the query is for an existing category archive page.
Description
If the $category parameter is specified, this function will additionally check if the query is for one of the categories specified.
For more information on this and similar theme functions, check out the Conditional Tags article in the Theme Developer Handbook.
Parameters
$categoryint|string|int[]|string[]optional-
Category ID, name, slug, or array of such to check against. Default empty.
Source
function is_category( $category = '' ) {
global $wp_query;
if ( ! isset( $wp_query ) ) {
_doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
return false;
}
return $wp_query->is_category( $category );
}
Changelog
| Version | Description |
|---|---|
| 1.5.0 | Introduced. |
Skip to note 2 content
Codex
Examples
is_category(); // When any Category archive page is being displayed. is_category( '9' ); // When the archive page for Category 9 is being displayed. is_category( 'Stinky Cheeses' ); // When the archive page for the Category with Name "Stinky Cheeses" is being displayed. is_category( 'blue-cheese' ); // When the archive page for the Category with Category Slug "blue-cheese" is being displayed. is_category( array( 9, 'blue-cheese', 'Stinky Cheeses' ) ); // Returns true when the category of posts being displayed is either term_ID 9, // or slug "blue-cheese", or name "Stinky Cheeses". // Note: the array ability was added in version 2.5.