在循环内部,您可以利用wp_get_post_terms() 返回与特定职位相关的所有条款。返回的此对象包含具有指定术语的所有属性的所有术语
考虑到这一点,您可以使用foreach 循环获取每个术语,然后检查每个术语的父级。对于孙子术语,您需要在此处进行一些额外检查,以确定父级或最高级术语父级
你可以这样做
$terms = wp_get_post_terms( $post->ID, \'category\' );
if ( !empty( $terms ) && !is_wp_error( $terms ) ){
    foreach ( $terms as $term ) {
        if ( $term->parent == 4 ) {
            //Do something if parent is 4
        }
    }
}
 编辑要使用更深层的类别,可以使用
get_ancestors() 获取所有级别并使用
in_array() 测试特定类别ID
您可以按如下方式扩展该功能:
$terms = wp_get_post_terms( $post->ID, \'category\' );
if ( !empty( $terms ) && !is_wp_error( $terms ) ){
    foreach ( $terms as $term ) {
        if( $term->parent != 4 && $term->parent == 0 )
            continue;
        if ( $term->parent == 4 || in_array( 4, get_ancestors( $term->term_id, \'category\' ) )) {
            //Do something if parent ID is 4
        } else {
            //Do nothing
        }
    }
}