2016-10-10 40 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); 

根据您的要求其他参数不强制。

相关问题