in_category()
最后更新于:2021-11-27 07:41:30
in_category( int|string|int[]|string[]$category, int|object$post=null)Checks if the current post is within any of the given categories.
参数
- $category
-
(int|string|int[]|string[]) (Required) Category ID, name, slug, or array of such to check against.
- $post
-
(int|object) (Optional) Post to check instead of the current post.
Default value: null
响应
(bool) True if the current post is in any of the given categories.
源文件
文件: gc-includes/category-template.php
function in_category( $category, $post = null ) {
if ( empty( $category ) ) {
return false;
}
return has_category( $category, $post );
}
<?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.gechiui.org/Function_Reference/in_category#Testing_if_a_post_is_in_a_descendant_category */ if ( ! function_exists( 'gcdocs_post_is_in_a_subcategory' ) ) { function gcdocs_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; } } ?>