Reputation: 2243
I have this code in my wordpress site which displays products I have:
<?php
$params = array('posts_per_page' => 5, 'post_type' => 'product');
$wc_query = new WP_Query($params);
?>
<ul>
<?php if ($wc_query->have_posts()) : ?>
<?php while ($wc_query->have_posts()) :
$wc_query->the_post(); ?>
<li>
<h3>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</h3>
<?php the_post_thumbnail(); ?>
<?php the_excerpt(); ?>
</li>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php else: ?>
<li>
<?php _e( 'No Products' ); ?>
</li>
<?php endif; ?>
</ul>
It works fine, but I would like to display products from the category I choose, how could I do that?
Upvotes: 2
Views: 2430
Reputation: 254373
Try the following:
<?php
// Here set your product category SLUG (can be multiple coma separated)
$product_categories = array('clothing');
$wc_query = new WP_Query( array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => 5,
'tax_query' => array( array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $product_categories,
'operator' => 'IN',
) )
) );
?>
<ul>
<?php if ($wc_query->have_posts()) : ?>
<?php while ($wc_query->have_posts()) :
$wc_query->the_post(); ?>
<li>
<h3>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</h3>
<?php the_post_thumbnail(); ?>
<?php the_excerpt(); ?>
</li>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php else: ?>
<li>
<?php _e( 'No Products' ); ?>
</li>
<?php endif; ?>
</ul>
Tested and works.
Upvotes: 3