试图获取当前类别的子类别

时间:2016-04-28 05:39:43

标签: ajax wordpress

我正在尝试使用wp_dropdown_categories获取当前类别的子类别。

点击类别,我想得到子类别。我确实尝试使用带有参数的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();    
    }
}

2 个答案:

答案 0 :(得分:2)

如果您现在正在获取类别,这是最好的,只要您的旧代码看起来有一个小错误,这就是您的类别无法正常显示的原因。只需改变你的

'hierarchical' => false, 

'hierarchical' => true,

所以,你的类别会很好地显示出来。

答案 1 :(得分: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>
    
  3. 供参考:click me