2016-04-28 117 views
1

我正在嘗試使用wp_dropdown_categories獲取當前類別的子類別。試圖獲取當前類別的子類別

onclick類別,我想要獲取子類別。我曾嘗試使用get_categories函數與參數,但它不給我子類別。雖然使用has_children給我空白陣列。

這是我的代碼:

add_action('wp_ajax_wp_get_subcategory', 'wp_get_subcategory'); 

function wp_get_subcategory() { 
    $parent_cat_ID = $_POST['selected_category']; 

    $args = array(
    'child_of' => $parent_cat_ID, 
    'taxonomy' => 'download_category', 
    'hide_empty' => 0, 
    'hierarchical' => false, 
    'depth' => 1, 
    'parent' => $parent_cat_ID 
    ); 

    if (isset($parent_cat_ID)) { 
     $has_children = get_categories($args); 

     if ($has_children) { 

      //wp_dropdown_categories($args); 
      foreach ($has_children as $category) { 

       $option = '<option value="'.$category->cat_ID.'">'; 
       $option .= $category->cat_name; 
       echo $option .= '</option>'; 

      } 
     } else { 
      ?><select name="sub_cat_disabled" id="sub_cat_disabled" disabled="disabled"><option>No child categories!</option></select><?php 
     } 
     die();  
    } 
} 
+0

現在我正在獲取子類別謝謝 – Bhavesh

回答

0

試試這兩個示例,我有一些參考的網站藉此。我但願這對你有用

  1. 列表小類如果查看的類別,和兄弟/姐妹 類如果子類別。

    <?php 
    
    if (is_category()) { 
    $this_category = get_category($cat); 
    } 
    ?> 
    
    <?php 
    if($this_category->category_parent) 
        $this_category = wp_list_categories('orderby=id&show_count=0 
        &title_li=&use_desc_for_title=1&child_of='.$this_category->category_parent."&echo=0"); 
        else $this_category = wp_list_categories('orderby=id&depth=1&show_count=0 
        &title_li=&use_desc_for_title=1&child_of='.$this_category->cat_ID.  "&echo=0"); 
        if ($this_category) { ?> 
    
        <ul> 
        <?php echo $this_category; ?> 
        </ul> 
        <?php } ?> 
    
  2. 假設你要顯示其子類別爲10類的類別,其類別「nicename」是「檔案」。

    <select name="event-dropdown"> 
    <option value=""><?php echo esc_attr_e('Select Event', 'textdomain'); ?></option> 
    <?php 
    $categories = get_categories(array('child_of' => 10); 
    foreach ($categories as $category) { 
    printf('<option value="%1$s">%2$s (%3$s)</option>', 
        esc_attr('/category/archives/' . $category->category_nicename), 
        esc_html($category->cat_name), 
        esc_html($category->category_count) 
        ); 
    } 
    ?> 
    </select> 
    

相關信息:click me

2

這是最好的,如果你現在得到的類別,只要您的舊代碼看起來有一個小的失誤,這就是爲什麼你的類無法正確顯示。只要改變你的

'hierarchical' => false, 

'hierarchical' => true, 

等等,你的類別將被很好地顯示出來。