Search code examples
phpwordpresswoocommerceshortcodeproduct

Get on sale products for Woocommerce product category archives using a Get request


I want to be able to show only products on sale for any of the categories I have on my website. I have seen that you can use Woocommerce shortcodes.

However my Wordpress theme is dynamic (it runs for all product categories) and I can't really create one page using a shortcode for each of the product categories (some categories are created "on the go" when I add new products).

Is there any way I can simply have a query string to return the category with only on sale products?

For example: https://www.website.com/clothing/dresses?on_sale=true

---EDIT:---

I am not using shortcodes, just want a simple solution for the query parameter.

Forgot to mention that on my case I always have values on the "_regular_price" and "_sale_price" regardless if is on sale or not. Here are the examples:

Product ON SALE (prices are different): enter image description here

Product NOT on sale (prices are the same): enter image description here


Solution

  • You need to alter the main query via the pre_get_posts filter.

    add_action( 'pre_get_posts', 'modify_query_show_on_sale_products' );
    
    function modify_query_show_on_sale_products( $query ) {
    
        if( ! is_admin() && $query->is_main_query() && $query->query_vars['wc_query'] == 'product_query' ) {
    
            $query->set('meta_key', '_sale_price');
            $query->set('meta_value', '0');
            $query->set('meta_compare', '>=');
        }
    
    }