[英]How to get the products by categories in woocommerce?
I am trying to get all the products by categories to create a menu. 我正在尝试按类别获取所有产品,以创建菜单。
The output should be like: 输出应类似于:
name of category1
product in category1
product in category1
product in category1
name of category2
product in category2
product in category2
product in category2
For this I am using this code: 为此,我使用以下代码:
<?php
$args = array(
'number' => $number,
'orderby' => $orderby,
'order' => $order,
'hide_empty' => $hide_empty,
'include' => $ids
);
$product_categories = get_terms('product_cat', $args);
?>
But do not how to get the result printed in that format mentioned above. 但是,不要以上述格式打印结果。
I am new to woocommerce and wordpress. 我是woocommerce和wordpress的新手。 Please help me. 请帮我。
You can do that by iterating categories you already fetched and list product under each categories like; 您可以通过迭代已经获取的类别并在每个类别下列出产品来做到这一点;例如:
$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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.