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


How to check if current post or category is descendant of certain category?

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

例如:

Cat1>Cat2>Cat3>Cat4>Post1atr

检查Post1是否为Cat1 的子级

并检查Cat4是否是Cat1 的子级

在上述情况下,此函数返回true。而CCD_ 11则不然。

<?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;
    }
}