NB: Make sure you do a back up of your theme, files and database before attempting the tutorials

Intermediate
Web Hosting Canada

Last modified : Sep 03 2022

Estimated reading time : 1 minute, 15 seconds - 135 words

This tutorial will show you how to create a function allowing you to display your best selling WooCommerce products. This query will include arguments that will check the WooCommerce “product” post type and use the meta query of the “total_sales” key.

We increment $i inside the loop so the sorting number of each result starts at 1. We also need the WooCommerce variable $product in the loop so it returns the products.

We want to display our WooCommerce products sorted by sales by making sure that the “total_sales” meta query key is superior to 0.

We also need another condition that specifies if $units_sold > 1 we need to use plural. Otherwise, it’s singular.

Here’s the code snippet to add into your WordPress plugin.

<?php 
$i = 1; $args = array( 
'post_type'       => 'product',
'meta_key'        => 'total_sales',
'orderby'         => 'meta_value_num',
'posts_per_page'  => 25,
'meta_query'      => array(
  array(
    'key'      => 'total_sales',
    'value'    => 0,
    'compare'  => '>'
    )
  )
);

$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); 
?>
<h3>
<a id="<?php the_id(); ?>" style="text-decoration: none;" title="<?php the_title(); ?>" href="<?php the_permalink(); ?>" target="_blank" rel="noopener">
     <?php echo $i; ?><?php the_title(); ?>
</a>
</h3>
<?php $i++; endwhile; ?>
<?php wp_reset_query(); ?>

This query also lets you edit your HTML and CSS.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>