2016-11-10 90 views
2

我建立一個房地產網站,所以我有很多類別3〜4 級別的子類別,但我的要求是隻顯示一個級別的子 類如父類SUB1,SUB2和SUB3的僅見結構我有這樣的如何只顯示一個級別的子類別?

- cat1 
    - sub1 
     - secondsub1 
- cat2 
    - sub2 
     - secondsub2 
- cat3 
    - sub3 
     - secondsub3 



$categories = get_terms(
        'category', 
        array('hide_empty' => 0,'parent' => 0,'number' =>3,'order'=> 'ASC') 
         ); 
foreach ($categories as $category) { 
      $catName= $category->term_id; 

<?php echo get_cat_name($catName); // this is the main category ?> 

<!-- subcategory code starts here--> 

     $args = array(
        'type' => 'post', 
        'child_of' => $catName, 
        'parent' => get_query_var(''), 
        'orderby' => 'name', 
        'order' => 'ASC', 
        'hide_empty' => 0, 
        'hierarchical' => 1, 
        'exclude' => '', 
        'include' => '', 
        'number' => '5', 
        'taxonomy' => 'category', 
        'pad_counts' => true); 
        $categories = get_categories($args); 
        foreach($categories as $category) { 
<a href="<?php echo get_category_link($category->term_id)?>" title="View posts in <?php echo $category->name?>"><?php $category->name;?></span><!--these are the sub category--> 
} 
} 

在結果類別下,我得到cate1 sub1-> secondsub1因爲 秒ondsub1也是孩子cat1但我只想sub1我怎麼能做到這一點?任何建議

回答

2

使用parent而不是child_of

parent(INT |字符串)父項ID檢索的直接子項。

來源:#parameters

+0

感謝回答我只是忘了我不應該使用child_of :) – RItika

2

你可以使用wp_list_categories((Developer Wordpress Reference)來獲取子類別爲每個類別的林不知道這個使用效率,但給它一個嘗試

左右。在你的代碼,會在這裏:

<!-- subcategory code starts here--> 
wp_list_categories(array(
    'child_of' => $category->term_id, 
    'depth'  => 1  
)); 

一些閱讀後我找到其他的解決辦法,這樣你就可以使用:

$args = array('parent' => $category->term_id); 
    $categories = get_categories($args); 
    foreach($categories as $category) { 
     <a href="<?php echo get_category_link($category->term_id)?>" title="View posts in <?php echo $category->name?>"><?php $category->name;?></span><!--these are the sub category--> 
    } 

也要照顧與使用「$類別」兩下,這可能會有點混亂。

+0

感謝您的回答,但我不想使用wp_list_categories第二個答案,你已經給作品感謝:) – RItika