我在这里获得2级产品类别,但我想要的产品超过2种。就像prodA-> proda1-> proda11
$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 :(得分: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 );
根据您的要求,其他参数不是强制性的。
答案 1 :(得分: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循环...
此代码经过测试并有效。