我想要wordpress woocommerce产品类别的输出如下:
<ul>
<li>categorie-with-sub
<ul>
<li>sub 1</li>
<li>sub 2</li>
<ul>
</li>
<li>category-without-sub</li>
<li>categorie-with-sub
<ul>
<li>sub 1</li>
<li>sub 2</li>
<ul>
</li>
但是下面的代码是:
<li>categorie-with-sub
<ul>
<li>sub 1</li>
<li>sub 2</li>
<ul>
</li>
<li>category-without-sub</li><ul>
<li>categorie-with-sub
<ul>
<li>sub 1</li>
<li>sub 2</li>
<ul>
</li>
我该怎么做才能解决问题?我尝试了很多方法。必须有能满足我要求的东西。
<?php
$taxonomy = 'product_cat';
$orderby = 'name';
$show_count = 1; // 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
);
?>
<?php $all_categories = get_categories( $args );
foreach ($all_categories as $cat) {
if($cat->category_parent == 0) {?>
<?php $category_id = $cat->term_id;
$thumbnail_id = get_woocommerce_term_meta( $cat->term_id, 'thumbnail_id', true );
$image = wp_get_attachment_url( $thumbnail_id );
echo '<li class="has-sub"><img src="'.$image.'" width="29px" height="29px" class="cat-img"/><a href="#"><span>'. $cat->name .'</span></a><ul>';
$cats = get_categories($args);
$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' => 1,
);
$sub_cats = get_categories( $args2 );
if($sub_cats) {
foreach($sub_cats as $sub_category) {
if($sub_cats->$sub_category == 0) {
$thumbnail_id = get_woocommerce_term_meta( $sub_category->term_id, 'thumbnail_id', true );
$image = wp_get_attachment_url( $thumbnail_id );
echo '<li><img src="'.$image.'" width="29px" height="29px" class="cat-img"/><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'.$sub_category->name.'</a></li>';
}
}
echo '</ul>';
}?>
<?php }
} ?>
非常感谢!
答案 0 :(得分:0)
$term = get_queried_object();
$children = get_terms( $term->taxonomy, array(
'parent' => $term->term_id,
'hide_empty' => false
) );
// print_r($children); // uncomment to examine for debugging
if($children) { // get_terms will return false if tax does not exist or term wasn't found.
// term has children
}
未经测试。
答案 1 :(得分:0)
$term = get_queried_object();
$children = get_terms( $term->taxonomy, array(
'parent' => $term->term_id,
'hide_empty' => false
) );
// print_r($children); // uncomment to examine for debugging
if($children) { // get_terms will return false if tax does not exist or term wasn't found.
// term has children
}
这有效,但必须略微修改。我不得不改变
$term = get_queried_object();
到
global $wp_query;
$term = $wp_query->get_queried_object();