如何在woocommerce中按类别获取产品?

时间:2014-07-22 09:30:24

标签: php wordpress woocommerce

我正在尝试按类别获取所有产品以创建菜单。

输出应该是:

    name of category1
      product in category1
      product in category1
      product in category1
   name of  category2
      product in category2
      product in category2
      product in category2

为此,我使用此代码:

<?php
                    $args = array(
                        'number' => $number,
                        'orderby' => $orderby,
                        'order' => $order,
                        'hide_empty' => $hide_empty,
                        'include' => $ids
                    );

                    $product_categories = get_terms('product_cat', $args);

                    ?>

但不要如何以上述格式打印结果。

我是woocommerce和wordpress的新手。请帮帮我。

1 个答案:

答案 0 :(得分:0)

您可以通过迭代已提取的类别并在每个类别下列出产品来完成此操作,例如:

$args = array(
    'number' => $number,
    'orderby' => $orderby,
    'order' => $order,
    'hide_empty' => $hide_empty,
    'include' => $ids
);

$product_categories = get_terms('product_cat', $args);
?>
<ul>
    <?php
        foreach ($product_categories as $cat) {
            ?>
                <li>
                    <a href="<?php echo get_term_link($cat->slug, 'product_cat'); ?>"><?php echo $cat->name;?></a>
                    <ul>
                        <?php
                        $productArgs = array( 'post_type' => 'product', 'posts_per_page' => 1, 'product_cat' => $cat->name, 'orderby' => 'rand' );
                        $products = new WP_Query( $productArgs );
                        while ( $products->have_posts() ) : $products->the_post(); global $product; ?>

                            <li><a href="<?php echo get_permalink( $products->post->ID ) ?>"><?php echo $products->post->title;?></a></li>

                        <?php endwhile; ?>
                    </ul>
                </li>

    <?php 
        }

    wp_reset_query(); ?>
</ul>