检查帖子是否在父类别的任何子类别中

时间:2014-07-21 作者:leemon

在我正在开发的网站中,我有以下类别结构:

* movies (parent)
    * thriller (child)
    * comedy (child)
    * drama (child)
当前职位位于comedy 类别这个has_term 具有以下参数的函数返回true:

has_term( \'comedy\', \'category\' )
但是,具有以下参数的同一函数返回false:

has_term( \'movies\', \'category\' )
我的问题是,是否有一个核心功能来检查当前帖子是否在特定父类别的任何子类别中?如果没有,我如何检查?

提前感谢

2 个回复
最合适的回答,由SO网友:Gabriel 整理而成

将以下内容添加到主题的功能中。php:

/**
 * Tests if any of a post\'s assigned categories are descendants of target categories
 *
 * @param int|array $cats 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)
 * @version 2.7
 * @link http://codex.wordpress.org/Function_Reference/in_category#Testing_if_a_post_is_in_a_descendant_category
 */
if ( ! function_exists( \'post_is_in_descendant_category\' ) ) {
    function post_is_in_descendant_category( $cats, $_post = null ) {
        foreach ( (array) $cats as $cat ) {
            // get_term_children() accepts integer ID only
            $descendants = get_term_children( (int) $cat, \'category\' );
            if ( $descendants && in_category( $descendants, $_post ) )
                return true;
        }
        return false;
    }
}
使用该函数检查父类别ID,而不是名称或slug。一、 e.如果“电影”类别ID为50:

if ( post_is_in_descendant_category( 50 ) ) {
    // do something
}
如果您不知道“movies”类别ID,可以使用get\\u term\\u by()检索ID,并将其传递给post\\u is\\u in\\u descendant\\u category():

$category_to_check = get_term_by( \'name\', \'movies\', \'category\' );

if ( post_is_in_descendant_category( $category_to_check->term_id ) ) {
    // do something
}

SO网友:Josef Wittmann

如果你愿意any nesting depth, 使用get_posts.

/**
 * Checks if the post is in one of the categories or any child category. 
 * 
 * @param  int|string|array $category_ids (Single category id) or (comma separated string or array of category ids).
 * @param  int              $post_id      Post ID to check. Default to `get_the_ID()`.
 * @return bool true, iff post is in any category or child category.
 */
function is_post_in_category( $category_ids, $post_id = null ) {
    $args = array(
        \'include\'  => $post_id ?? get_the_ID(),
        \'category\' => $category_ids,
        \'fields\'   => \'ids\',
    );
    return 0 < count( get_posts( $args ) );
}
您可以通过多种方式扩展此函数。可能会传递一个post id数组并过滤掉一些,或者允许对查询进行优化。

结束