gpt4 book ai didi

php - 获取带有子类别的 woocommerce 类别

转载 作者:行者123 更新时间:2023-12-03 22:53:58 25 4
gpt4 key购买 nike

我想在前端获得所有 woocommerce 类别的子类别,如下所示:

<ul>
<li><a href="">Link</a>
<ul>
<li><a href="">Submenu link</a></li>
</ul>
</li>
</ul>

这是我所拥有的(但这不是我想要的):
<?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>';
}
}
}
}
?>

这段代码显示了类别和子类别,但子类别不是应该在的地方,子类别就像这样的单独链接:
<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 的站点中打印。

关于php - 获取带有子类别的 woocommerce 类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43465051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com