简体   繁体   中英

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): 在此处输入图片说明

Product NOT on sale (prices are the same): 在此处输入图片说明

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', '>=');
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM