In this tutorial we’ll learn how to fetch only those products that have images. By default Woocommerce displays all the products whether or not they have images. If a product doesn’t have any image Woocommerce will display an image placeholder instead. So, now we want to display products whose images are set.
Here is my default product archive screen i.e. shop and category pages.
Currently it is displaying all products, with or without product images.
Now we need to remove those products that don’t have product images. To do this go to admin panel of your site and click on installed plugins section under plugins. Click on the edit link under woocommerce.
Now here look for the template archive-product.php and click Edit to open the file.
Find the following code :
<?php while ( have_posts() ) : the_post(); ?> <?php wc_get_template_part( 'content', 'product' ); ?> <?php endwhile; // end of the loop. ?>
And replace it with this:
<?php $args = array( 'post_type' => 'product', 'stock' => 1, 'posts_per_page' => 9, 'orderby' =>'date', 'orderby' => 'rand', 'meta_query'=>array( array( 'key'=>'_thumbnail_id', 'compare' => 'EXISTS' ) ) ); $loop = new WP_Query( $args ); while ($loop->have_posts()) : $loop->the_post(); //echo get_the_post_thumbnail($loop->post->ID, 'shop_catalog'); wc_get_template_part( 'content', 'product' ); endwhile; ?>
Now if you go to archive product page, you’ll only see products with images. Thanks