Wordpress - >仅显示第二级别类别

时间:2016-12-14 00:41:51

标签: php wordpress post

我希望在查看单个帖子时排除顶级和3级以上的帖子类别。摆脱顶级水平是没有问题的,但不确定我如何去除3级以上。任何人都可以阐明如何处理这个问题?

这就是我现在所拥有的:

$categories = get_the_terms( $post->ID, 'category' );
// now you can view your category in array:
// using var_dump( $categories );
// or you can take all with foreach:
foreach( $categories as $category ) {
    var_dump($category);
    if($category->parent) echo $category->term_id . ', ' . $category->slug . ', ' . $category->name . '<br />';
}

1 个答案:

答案 0 :(得分:1)

要获得第二级,您需要运行两个循环 - 一个用于标识顶级的ID,以便您可以识别具有父ID的类别,即在顶层(这意味着它是第二级)。

$categories = get_the_terms( $post->ID, 'category' );

// Set up our array to store our top level ID's
$top_level_ids = [];
// Loop for the sole purpose of figuring out the top_level_ids
foreach( $categories as $category ) {
    if( ! $category->parent ) {
        $top_level_ids[] = $category->term_id;
    }
}

// Now we can loop again, and ONLY output terms who's parent are in the top-level id's (aka, second-level categories)
foreach( $categories as $category ) {
    // Only output if the parent_id is a TOP level id
    if( in_array( $category->parent_id, $top_level_ids )) {
        echo $category->term_id . ', ' . $category->slug . ', ' . $category->name . '<br />';
    }
}
相关问题