2016-12-14 41 views
1

我想在查看单个帖子时排除顶级和3+级别的帖子类别。摆脱顶级是没有问题的,但不知道如何去除3级以上。任何人都可以阐明如何处理这个问题?WordPress的 - >仅显示第二级类别

这是我现在有:

$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

要获得第二个层次,你要运行两个环路 - 一个识别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 />'; 
    } 
} 
+0

好的,这是有道理的。跟踪顶级ID并使用该数据评估...好主意。感谢您的洞察! – wutang