2016-04-28 116 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, 

等等,你的类别将被很好地显示出来。