2016-12-14 11 views
1

1つの投稿を表示するときにトップレベルと3+レベルの投稿カテゴリを除外します。トップレベルを取り除くことは問題ありませんが、どうすれば3+レベルを削除するのか分かりません。誰もこれに対処する方法について光を当てることができますか?Wordpress - > 2番目のレベルのカテゴリのみを表示

これは私が今持っているものです: - あなたが識別できるように、1つのトップレベルのIDを識別するための

$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

セカンドレベルを取得するには、次の2つのループを実行することをお勧めしますトップレベルにある親IDを持つカテゴリ(2番目のレベルを意味します)。

$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

関連する問題