使用WooCommerce按类别显示所有产品

时间:2014-03-25 作者:JacobTheDev

在WooCommerce中,我想将商店中的所有类别显示为标题,并将其所有产品列在下面的无序列表中。这可能吗?我看到了一些可以让我显示类别列表或特定类别的产品列表的东西,但没有任何东西可以像我描述的那样循环遍历所有内容。

以下是我目前用于列出所有类别的内容:

<?php
$args = array(
    \'number\'     => $number,
    \'orderby\'    => $orderby,
    \'order\'      => $order,
    \'hide_empty\' => $hide_empty,
    \'include\'    => $ids
);
$product_categories = get_terms( \'product_cat\', $args );
$count = count($product_categories);
if ( $count > 0 ){
    foreach ( $product_categories as $product_category ) {
        echo \'<h4><a href="\' . get_term_link( $product_category ) . \'">\' . $product_category->name . \'</h4>\';
    }
}
?> 

1 个回复
最合适的回答,由SO网友:JacobTheDev 整理而成

算了吧!下面的代码会自动列出所有类别和每个类别的帖子!

$args = array(
    \'number\'     => $number,
    \'orderby\'    => \'title\',
    \'order\'      => \'ASC\',
    \'hide_empty\' => $hide_empty,
    \'include\'    => $ids
);
$product_categories = get_terms( \'product_cat\', $args );
$count = count($product_categories);
if ( $count > 0 ){
    foreach ( $product_categories as $product_category ) {
        echo \'<h4><a href="\' . get_term_link( $product_category ) . \'">\' . $product_category->name . \'</a></h4>\';
        $args = array(
            \'posts_per_page\' => -1,
            \'tax_query\' => array(
                \'relation\' => \'AND\',
                array(
                    \'taxonomy\' => \'product_cat\',
                    \'field\' => \'slug\',
                    // \'terms\' => \'white-wines\'
                    \'terms\' => $product_category->slug
                )
            ),
            \'post_type\' => \'product\',
            \'orderby\' => \'title,\'
        );
        $products = new WP_Query( $args );
        echo "<ul>";
        while ( $products->have_posts() ) {
            $products->the_post();
            ?>
                <li>
                    <a href="<?php the_permalink(); ?>">
                        <?php the_title(); ?>
                    </a>
                </li>
            <?php
        }
        echo "</ul>";
    }
}

结束