2016-11-30 82 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