检查当前帖子是否在父类别或其子类别中

问题描述

我有 200 多个类别,我需要能够检查当前类别(在 category.PHP 上)是否在父类别数组中。

我已经阅读了大量方法来检查帖子是否属于某个类别或子类别,或者一只猫是否是另一只猫的孩子或父母。但是我找不到任何关于检查当前猫是否在父类别数组中的 WP 函数或问题。

这是我想要完成的:

  • 父母 1(ID 1)
    • 孩子 1(ID 5)
    • 孩子 2(ID 6)
    • 孩子 3(ID 7)
      • 孙子 1 (ID 8)
  • 父母 2(ID 2)
  • 父 3(ID 3)
  • 家长 4 (ID 4)

我需要做这样的事情:

IF( cat_is_child_of( array(1,2,3,4)) ):
    Do something amazing
ELSE
    The current category is NOT within any of the parent categories for the ID's given
ENDIF

有什么想法吗???

        <?PHP if (
                is_post_type_archive( 'inventory' ) 
                || get_post_type( get_the_ID() ) == 'inventory' 
                  // check if category IS one of these parent cats
                || is_category(array( 25,28,124,297,298,299 )) 
                  // ugly version of checking if this cat is SUB of any parent cats
                || cat_is_ancestor_of(25,get_query_var( 'cat' ))
                || cat_is_ancestor_of(124,get_query_var( 'cat' ))
                || cat_is_ancestor_of(297,get_query_var( 'cat' ))
                || cat_is_ancestor_of(298,get_query_var( 'cat' ))
                || cat_is_ancestor_of(299,get_query_var( 'cat' ))
            ):
            ?>

解决方法

经过大量搜索并且只提出了检查类别是否有子类别的功能,或者帖子是否在(只是)子类别中,我遇到了一个带有有效功能的旧帖子:

if ( ! function_exists( 'post_is_in_a_subcategory' ) ) {
function 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;
  }
}

以及我如何使用它:

        <?php if (
            is_post_type_archive( 'inventory' ) 
            || get_post_type( get_the_ID() ) == 'inventory' 
            // in one of the parent cats?
            || is_category(array( 25,28,124,297,298,299 )) 
            // in ANY of the subcats?
            || post_is_in_a_subcategory( array( 25,299 ) )
            
        ):
        ?>

例如,原始功能在 Wordpress 法典中,不在核心中。 http://codex.wordpress.org/Function_Reference/in_category#Testing_if_a_post_is_in_a_descendant_category 它已被删除!