FrontEnd DevelopmentTechnical DevelopementWeb Application

Get a List of Products on Sale in WooCommerce

Check if the product is on sale

We can simply check if a product is on sale by using is_on_sale() function.

<?php

global $product;
if ( $product->is_on_sale() ) {
    // wow product is on sale
    // do something
}

Get Products on Sale from All Categories

On contrary, getting a list of products that are on sale is a bit complex than check for a single product. We will use WP_QUERY class. In addition, we will use wc_get_product_ids_on_sale() function to get all the ids.

<?php
//arguments
$args = array(
    'posts_per_page'    => 24,
    'post_status'       => 'publish',
    'post_type'         => 'product',
    'meta_query'        => WC()->query->get_meta_query(),
    'post__in'          => array_merge( array( 0 ), wc_get_product_ids_on_sale() )
);

//get products on sale using wp_query class
$products = new WP_Query( $args );

<?php if($products->have_posts()) : ?>
    <?php while($products->have_posts()) : $products->the_post(); ?>
        <?php the_title() ?>
        <?php echo $product->get_price(); ?>
        <?php echo $product->get_sale_price(); ?>
    <?php endwhile; ?>
<?php else : ?>
    <p> Sorry!No products on sale</p>
<?php endif; ?>

The above query will retrieve all the products that are on sale from all category.

Get Products on Sale from Specific Categories

We can also retrieve list of products from specific categories. For this we should pass ids of categories as an array.

<?php

$categories = array(1, 4, 7); //ids of categories

$query_args = array(
      'post_status'       => 'publish',
      'post_type'         => 'product',
      'posts_per_page'    => 24,
      'orderby'           => 'ASC',
      'meta_query'        => WC()->query->get_meta_query(),
      'post__in'          => array_merge( array( 0 ), wc_get_product_ids_on_sale() ),
);

$query_args['tax_query'] = array(
    array(
        'taxonomy' => 'product_cat',
        'field' => 'term_id',
        'terms' => $categories,
        'operator' => 'IN',
  ));

 $products = new WP_Query( $query_args );
 
 <?php if($products->have_posts()) : ?>
    <?php while($products->have_posts()) : $products->the_post(); ?>
        <?php the_title() ?>
        <?php echo $product->get_price(); ?>
        <?php echo $product->get_sale_price(); ?>
    <?php endwhile; ?>
<?php else : ?>
    <p> Sorry!No products on sale</p>
<?php endif; ?>

Author: NghiaMP