2013-02-27 77 views
8

我使用這段代碼:的WordPress:只顯示頂級類別

$args = array(
    'orderby' => 'name', 
    'hierarchical' => 1, 
    'style' => 'none', 
    'taxonomy' => 'category', 
    'hide_empty' => 0, 
    'depth' => 1, 
    'title_li' => '' 
); 

$categories = get_categories($args); 

我所試圖做的是隻列出頂級類別。當我使用這個代碼時,我將它們全部放在第一層。有人能幫我嗎?

+1

沒有爲get_categories沒有深度參數()-http://codex.wordpress.org/Function_Reference/get_categories深度參數在wp_list_categories()中使用 - http://codex.wordpress.org/Template_Tags/wp_list_categories – McNab 2013-02-27 13:30:01

回答

22

沒有depth論據get_categories(),你應該嘗試:

$args = array(
    'orderby' => 'name', 
    'parent' => 0 
); 

parent: (整數)僅顯示直接後裔類別(即兒童專用)查明的類別它的ID。這不適用於'child_of'參數。此參數沒有默認值。 [在2.​​8.4]

瞭解更多:http://codex.wordpress.org/Function_Reference/get_categories#Get_only_top_level_categories

+0

如何僅顯示一個級別的子類別? 例如:我想隱藏一級子類別的子類別 – 2014-08-12 13:00:14

+0

感謝燒酒,它的幫助很大:) – Max 2016-04-25 14:42:48

2

燒酒職位是非常有幫助的,對於只得到1類一級子類別,我們應該只通過有子類別的類別ID。但是,如果子類沒有任何職位則亙古不顯示,但子類別的子類別包括後這麼加「hide_empty」 => 0,在上述條件下它看起來就像

$args = array(
'taxonomy' => 'categories', 
'parent' => 7, 
'hide_empty' => 0, 
); 
0

這裏是我的腳本來獲得最高級別循環中的類別名稱。這將包括只檢查了一個子類別的頂級類別,並且沒有明確檢查它們自己。

<?php 
    $categories = get_the_category(); 
    $topcats = array(); 
    foreach ($categories as $cat) { 
     if ($cat->parent != 0) $cat = get_term($cat->parent, 'category'); 
     $topcats[$cat->term_id] = '<a href="/category/' . $cat->slug . '">' . $cat->name . '</a>'; 
    } 
    echo implode(', ', $topcats); 
?>