描述
根据文章类别的term_id、name和slug检查给定类别。以整数形式给出的类别将仅根据文章的类别的term_ID进行检查。
在WordPress v2.5之前,类别名称不受支持。在v2.7之前,不支持slug。在v2.7之前,只能比较一个类别:in_category( $single_category )。在v2.7之前,该函数只能在WordPress循环中使用。从2.7开始,如果提供post ID或post对象,则该函数可以在任何地方使用。
更多类似的主题函数信息,请查看主题开发手册中的条件标签文章。
参数
- $category
-
(int|string|int[]|string[]) (必填) 要检查的类别ID、name、slug或其数组。
- $post
-
(int|object) (可选) 要检查的文章,而不是当前文章。
默认值: null
返回
(bool) 如果当前文章属于给定类别,则为true。
源码
更新日志
版本 | 描述 |
---|---|
2.7.0 | 添加了$post 参数 |
1.2.0 | 开始引入 |
使用示例
在循环外测试当前文章
在请求单个文章(通常由single.php模板处理)的过程中,您甚至可以在循环开始之前测试该文章的类别。您可以使用此选项切换模板,如下所示:
if ( in_category('fruit') ) { include 'single-fruit.php'; } elseif ( in_category('vegetables') ) { include 'single-vegetables.php'; } else { // Continue with normal Loop if ( have_posts() ) : while ( have_posts() ) : the_post(); // ... }
(自定义文章模板插件允许为单个文章创建模板。它还展示了如何添加模板的示例,该模板用于给定类别中的所有文章,而不仅仅是单个文章。默认情况下,该示例在插件中被注释掉,但可以通过取消注释适当的行来轻松实现。)
在循环中测试当前文章
in_category()
通常用于根据当前文章的类别在循环中采取不同的操作,例如:if ( in_category( 'pachyderms' )) { // They have long trunks... } elseif ( in_category( array( 'Tropical Birds', 'small-mammals' ) )) { // They are warm-blooded... } else { // etc. }
要检查文章是否在父类别或其任何子类别内,请执行以下操作:
<?php /** * Tests if any of a post's assigned categories are descendants of target categories * * @param int|array $categories The target categories. Integer ID or array of integer IDs * @param int|object $_post The post. Omit to test the current post in the Loop or main query * @return bool True if at least 1 of the post's categories is a descendant of any of the target categories * @see get_term_by() You can get a category by name or slug, then pass ID to this function * @uses get_term_children() Passes $cats * @uses in_category() Passes $_post (can be empty) * @link originally at https://codex.wordpress.org/Function_Reference/in_category#Testing_if_a_post_is_in_a_descendant_category */ if ( ! function_exists( 'wpdocs_post_is_in_a_subcategory' ) ) { function wpdocs_post_is_in_a_subcategory( $categories, $_post = null ) { foreach ( (array) $categories as $category ) { // get_term_children() only accepts integer ID $subcats = get_term_children( (int) $category, 'category' ); if ( $subcats && in_category( $subcats, $_post ) ) return true; } return false; } } ?>
用于检查是否在单个cat内:
wpdocs_post_is_in_a_subcategory( 25 );
用于检查是否在父类别或其任何子类别的数组中:
wpdocs_post_is_in_a_subcategory( array( 25, 28, 124, 297, 298, 299 ) );