首页 > 解决方案 > 检查当前帖子是否在父类别或其子类别中

问题描述

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

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

这是我要完成的工作:

我需要做这样的事情:

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' ))
            ):
            ?>

标签: wordpressfunctioncategoriesarchive

解决方案


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

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,28,124,297,298,299 ) )
            
        ):
        ?>

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


推荐阅读