Exclude WooCommerce products with no reviews from a WP_Query

Viewed 148

I was trying to list 10 Popular Products based on total sales in a WooCommerce website using a custom query. But the same time product with zero/no reviews has to be Excluded from the listing. Any methods to achieve this?

Following are the code:

<?php
   global $woocommerce;
   global $product;
   $args = array(
      'post_type' => 'product',
      'posts_per_page' => 10,
      'meta_key' => 'total_sales',
      'orderby' => 'meta_value_num'
   );
   $popular_products = new WP_Query($args);
   if($popular_products->have_posts()):
?>
<ul>
    <?php 
       while ($popular_products->have_posts()) : $popular_products->the_post();
       $product = wc_get_product( get_the_ID() );
       $rating = round($product->get_average_rating()); 
    ?>
    <li>
        <h3><?php the_title(); ?></h3>
        <div><?php the_post_thumbnail(); ?></div>
        <p><strong>Rating: </strong><?php echo $rating; ?>/5</p>
        <a href="<?php the_permalink(); ?>">View Product</a>
    </li>
    <?php 
      endwhile; 
      wp_reset_postdata(); 
    ?>
</ul>
<?php endif; ?>

I came to know about 'post__not_in', but not sure how to use it with product rating. Any help would be appreciated.

1 Answers

The following will additionally exclude Product with Zero/No reviews:

<?php
$products = new WP_Query( array(
    'post_type'      => 'product',
    'posts_per_page' => 10,
    'meta_key'       => 'total_sales',
    'orderby'        => 'meta_value_num',
    'meta_query'     => array( array(
        'key'        => '_wc_review_count',
        'value'      => '0',
        'compare'    => '>',
    )),
));

if( $products->have_posts() ): 
    ?>
    <ul>
    <?php 
    while ( $products->have_posts() ) : $products->the_post();
        $_product = wc_get_product( get_the_ID() );
        $rating   = round( $_product->get_average_rating() ); 
        ?>
        <li>
            <h3><?php the_title(); ?></h3>
            <div><?php the_post_thumbnail(); ?></div>
            <p><strong>Rating: </strong><?php echo $rating; ?>/5</p>
            <a href="<?php the_permalink(); ?>">View Product</a>
        </li>
    <?php 
    endwhile; 
    wp_reset_postdata(); 
    ?>
    </ul>
<?php endif; ?>

Note that global $woocommerce; and global $product; are not needed…

Related