[SOLVED] Woocommerce: Show only products on offer on independent page

Issue

I want to create an independent page called “discounts” and show all the products on offer, I have the following function added to my son theme but it makes the main page of the store (with all products) show only products on offer, as I can have This function but only on a specific page? It occurs to me to perform an “empty” search to show all discounted products (using this function), am I going the right way?

add_action( 'woocommerce_product_query', 'onsale_custom' );

function onsale_custom( $q ){

    $product_ids_on_sale = wc_get_product_ids_on_sale();

    $q->set( 'post__in', $product_ids_on_sale );

}

Solution

You need to have a way to distinguish between the different pages,

What I’ve done to solve this issue was to create a new empty product category under the slug discounts (slug name can be changed, but keep track of it).

Then I’ve modified the function you attached to check if this category is being watched, via the is_product_category while providing the category slug name when calling this function.

Then settings the post__in query arg and un-setting the product_category to allow all products that are on-sale to be viewed.

This is the result:


add_action( 'woocommerce_product_query', 'onsale_custom' );
function onsale_custom( $query ){
        if ( is_product_category('discounts') ) { // My slug name is 'discounts'
            $product_ids_on_sale = wc_get_product_ids_on_sale();
            $query->set( 'post__in', $product_ids_on_sale );
            unset ($query->query_vars['product_cat']);
        }
}

Answered By – H. Bloch

Answer Checked By – David Goodson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.