2016-12-14 38 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