如何检查当前帖子或类别是否属于某类别的后代?

时间:2016-05-03 13:35:54

标签: php wordpress wordpress-theming

我想知道如何检查当前的单个帖子或当前类别是否为具有任何深度的特定类别的孩子。

例如:

Cat1> Cat2> Cat3> Cat4> Post1

检查Post1是否为Cat1

的孩子

并检查Cat4是否为Cat1

的孩子

1 个答案:

答案 0 :(得分:1)

此函数在上述情况下返回true。和false否则。

<?php
function post_or_category_descendant_of( $category_id ) {
    if( is_category() && ( is_category( $category_id ) || cat_is_ancestor_of( $category_id, get_queried_object() ) ) ) {
        return true;

    } else if( is_single() ){

        $post_id = get_queried_object()->id;
        $post_categories = get_the_category( $post_id );

        $post_cat_ids = array();

        foreach( $post_categories as $pc ) {
            $post_cat_ids[] = $pc->cat_ID;
        }

        $args = array( 'child_of' => $category_id, 'fields' => 'ids' );
        $target_cat_ids = get_categories( $args );
        $target_cat_ids[] = $category_id;

        if( array_intersect( $post_cat_ids, $target_cat_ids ) ) {
            return true;
        } else {
            return false;
        }

    } else {
        return false;
    }
}
相关问题