如何通过类别ID获取woocommerce的第三类别

时间:2019-07-31 15:41:52

标签: wordpress woocommerce

我尝试使用此代码通过woocommerce类别ID显示多子类别,但出现错误。你能告诉我怎么了吗?

    $args = array(
        'hierarchical' => 1,
        'show_option_none' => '',
        'hide_empty' => 0,
        'parent' => $number = 66,
        'taxonomy' => 'product_cat'
    );
    $subcats = get_categories($args);
    echo '<div class="second-menu">';
        foreach ($subcats as $sc) {
            $link = get_term_link($sc->slug, $sc->taxonomy);
            echo '<li><a href="' . $link . '">' . $sc->name . '</a>' . '</li>';
                $args2 = get_terms('product_cat',array(
                    'child_of' => $sc->term_id,
                    'hierarchical' => 1,
                    'hide_empty' => 1,
                ));
            }
    echo '</div>';
    echo '<div class="third-menu">';
            foreach ($args2 as $subsubCats) {
                $SubLinks = get_term_link($subsubCats->slug, $subsubCats->taxonomy);
                echo '<li><a href=' . $SubLinks . '>' . $subsubCats->name . '</a>' .'</li>';
                }
    echo '</div>';
    wp_reset_query(); 

1 个答案:

答案 0 :(得分:2)

好的,现在我从您的代码中得到了问题。由于您需要2个子类别级别,因此您正在编写2个foreach循环,这是正确的,但是您需要添加第二个foreach循环作为第一个foreach的嵌套循环。我对您的代码做了一些更改,以获取2级子类别和正确的布局。

$args = array(
    'hierarchical' => 1,
    'show_option_none' => '',
    'hide_empty' => 0,
    'parent' => $number = 66,
    'taxonomy' => 'product_cat'
);
$subcats = get_categories($args);
echo '<div class="second-menu">';
echo '<ul>';
foreach ($subcats as $sc) {
    $link = get_term_link($sc->slug, $sc->taxonomy);
    echo '<li><a href="' . $link . '">' . $sc->name . '</a>';
        echo '<div class="third-menu">';
            $args2 = get_terms('product_cat', array(
                'child_of' => $sc->term_id,
                'hierarchical' => 1,
                'hide_empty' => 1
            ));
            echo '<ul>';
                foreach ($args2 as $subsubCats) {
                    $SubLinks = get_term_link($subsubCats->slug, $subsubCats->taxonomy);
                    echo '<li><a href=' . $SubLinks . '>' . $subsubCats->name . '</a>' . '</li>';
                }
            echo '</ul>';
        echo '</div>';
    echo '</li>';
}
echo '</ul>';
echo '</div>';

wp_reset_query();