2016-11-30 108 views
0

如何获取woocommerce中的分类列表? 有了这个代码,我得到WordPress的类别列表:显示woocommerce分类列表

function gaga_lite_category_lists(){ 
    $categories = get_categories(
     array(
      'hide_empty' => 0, 
      'exclude' => 1 
     ) 
    ); 


$category_lists = array(); 
$category_lists[0] = __('Select Category', 'gaga-lite'); 
foreach($categories as $category) : 
    $category_lists[$category->term_id] = $category->name; 
endforeach; 
return $category_lists; 

} 

我想woocommerce类来代替它。

+0

你只想要父类别列表? –

回答

1

WooCommerce产品类别都被视为product_cattaxonomy

这里是代码。

function gaga_lite_category_lists() 
{ 
    $category_lists = array(); 
    $category_lists[0] = __('Select Category', 'gaga-lite'); 
    $args = array(
     'taxonomy' => 'product_cat', 
     'orderby' => 'name', 
     'hierarchical' => 0, // 1 for yes, 0 for no 
     'hide_empty' => 0, 
     'exclude' => 1 //list of product_cat id that you want to exclude (string/array). 
    ); 
    $all_categories = get_categories($args); 
    foreach ($all_categories as $cat) 
    { 
     if ($cat->category_parent == 0) 
     { 
      $category_lists[$cat->term_id] = $cat->name; 
      //get_term_link($cat->slug, 'product_cat') 
     } 
    } 
    return $category_lists; 
} 
0

你可以使用下面的代码的所有Woocommerce类别和子类:

$taxonomy  = 'product_cat';//Woocommerce taxanomy name 
    $orderby  = 'name'; 
    $show_count = 0;  //set 1 for yes, 0 for no 
    $pad_counts = 0;  //set 1 for yes, 0 for no 
    $hierarchical = 1;  //set 1 for yes, 0 for no 
    $title  = ''; 
    $empty  = 0; 

    $args = array(
     'taxonomy'  => $taxonomy, 
     'orderby'  => $orderby, 
     'show_count' => $show_count, 
     'pad_counts' => $pad_counts, 
     'hierarchical' => $hierarchical, 
     'title_li'  => $title, 
     'hide_empty' => $empty 
); 

//get all woocommerce categories on the basis of $args 
$get_all_categories = get_categories($args); 
foreach ($get_all_categories as $cat) { 
    if($cat->category_parent == 0) { 
     $category_id = $cat->term_id;  
     echo '<br /><a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .'</a>'; 

     //Create arguments for child category 
     $args2 = array(
       'taxonomy'  => $taxonomy, 
       'child_of'  => 0, 
       'parent'  => $category_id, 
       'orderby'  => $orderby, 
       'show_count' => $show_count, 
       'pad_counts' => $pad_counts, 
       'hierarchical' => $hierarchical, 
       'title_li'  => $title, 
       'hide_empty' => $empty 
     ); 

     //Get child category 
     $sub_cats = get_categories($args2); 
     if($sub_cats) { 
      foreach($sub_cats as $sub_category) { 
       echo $sub_category->name ; 
      } 
     } 
    }  
} 

我希望这会帮助你。谢谢

+0

代码只回答arent鼓励,因为他们不提供很多信息为未来的读者请提供一些解释,你写了什么 – WhatsThePoint