2016-10-10 61 views
2

在這裏,我得到的產品的2級類別,但我想比2.Like prodA-更多> proda1-> proda11如何在wordpress中找到包含子類別等的產品類別?

$taxonomy = 'product_cat'; 
$all_categories = get_categories(array("taxonomy" =>"product_cat","parent" => 0)); 
echo "<pre>"; 
print_r($all_categories); 
die(); 
foreach ($all_categories as $cat) { 
    echo $category_id = $cat->term_id;  
    echo "parent name ==". $cat->name; 
    $sub = get_categories(array("taxonomy" => "product_cat", "parent" => $category_id)); 
    echo "<pre>"; print_r($sub); 
} 

回答

0

要通過類別迭代,和子類別您可以使用多個嵌入foreach循環是這樣的:

$taxonomy  = 'product_cat'; 
$categories = get_categories(array(
    'taxonomy' => $taxonomy, 
    'orderby'  => 'name', 
    'empty'  => 0, 
    'parent' => 0, 
)); 
echo "<div>"; 
foreach ($categories as $category) { 
    echo '<a href="' . get_term_link($category->slug, 'product_cat') . '">' . $category->name . ' (' . $category->term_id . ')</a><br>'; 

    $subcategories = get_categories(array(
     'taxonomy' => $taxonomy, 
     'orderby'  => 'name', 
     'empty'  => 0, 
     'parent' => $category->term_id, 
    )); 

    foreach ($subcategories as $subcategory) { 
     echo ' — <a href="' . get_term_link($subcategory->slug, 'product_cat') . '">' . $subcategory->name . ' (' . $subcategory->term_id . ')</a><br>'; 

     $subsubcats = get_categories(array(
      "taxonomy" => $taxonomy, 
      'orderby'  => 'name', 
      'empty'  => 0, 
      'parent' => $subcategory->term_id, 
     )); 

     foreach ($subsubcats as $subsubcat) 
      echo ' — — <a href="' . get_term_link($subsubcat->slug, 'product_cat') . '">' . $subsubcat->name . ' (' . $subsubcat->term_id . ')</a><br>'; 
    } 
} 
echo "</div>"; 

走得更遠比子類2級,將需要爲每個附加級別的嵌入額外的foreach循環...

此代碼已經過測試並可正常工作。

+0

謝謝!它的工作 –

0

請使用此代碼監守的,如果你沒有添加hide_empty => 0那麼一些獨立的類別產品是沒有顯示在你的下拉列表中。

$args = array(
    'type'      => 'product', 
    'child_of'     => 0, 
    'parent'     => '', 
    'orderby'     => 'term_group', 
    'hide_empty'    => false, 
    'hierarchical'    => 1, 
    'exclude'     => '', 
    'include'     => '', 
    'number'     => '', 
    'taxonomy'     => 'product_cat', 
    'pad_counts'    => false 
); 

$cats = get_categories($args); 

根據您的要求其他參數不強制。

相關問題