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. 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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.