获取带有子类别的 woocommerce 类别 [英] get woocommerce categories with subcategory
本文介绍了获取带有子类别的 woocommerce 类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在前端获得所有 woocommerce 类别的子类别,如下所示:
I want to get all woocommerce category's in front-end with subcategory like this result:
<ul>
<li><a href="">Link</a>
<ul>
<li><a href="">Submenu link</a></li>
</ul>
</li>
</ul>
这是我所拥有的(但这不是我想要的):
Here is what i have (But it's Not what i want) :
<?php
$taxonomy = 'product_cat';
$orderby = 'name';
$show_count = 0; // 1 for yes, 0 for no
$pad_counts = 0; // 1 for yes, 0 for no
$hierarchical = 1; // 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
);
$all_categories = get_categories( $args );
foreach ($all_categories as $cat) {
if($cat->category_parent == 0) {
$category_id = $cat->term_id;
echo '<li><a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .'</a></li>';
$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
);
$sub_cats = get_categories( $args2 );
if($sub_cats) {
foreach($sub_cats as $sub_category) {
echo '<li><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a></li>';
}
}
}
}
?>
此代码显示了类别和子类别,但子类别不在应有的位置,子类别就像这样的单独链接:
this code show's category and subcategory but the subcategory is not where should be, the subcategory is like separate link like this:
<ul>
<li><a href="">link</a></li>
<li><a href="">Submenu link</a></li>
</ul>
推荐答案
你可以试试这个代码:
$args = array(
'taxonomy' => 'product_cat',
'hide_empty' => false,
'parent' => 0
);
$product_cat = get_terms( $args );
foreach ($product_cat as $parent_product_cat)
{
echo '
<ul>
<li><a href="'.get_term_link($parent_product_cat->term_id).'">'.$parent_product_cat->name.'</a>
<ul>
';
$child_args = array(
'taxonomy' => 'product_cat',
'hide_empty' => false,
'parent' => $parent_product_cat->term_id
);
$child_product_cats = get_terms( $child_args );
foreach ($child_product_cats as $child_product_cat)
{
echo '<li><a href="'.get_term_link($child_product_cat->term_id).'">'.$child_product_cat->name.'</a></li>';
}
echo '</ul>
</li>
</ul>';
}
这将在基于 WooCommerce、Wordpress 的站点中打印.
This will Print in your WooCommerce, Wordpress based site.
这篇关于获取带有子类别的 woocommerce 类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文