WooCommerce: Display ONLY on-sale products in Shop

前端 未结 5 1383
花落未央
花落未央 2020-12-08 11:57

I need to create a products archive page (usually the Shop page in WooCommerce) but displays ONLY the ON SALE<

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-08 12:28

    @gmaggio using query_posts() will break your site. Use pre_get_posts

    add_filter( 'pre_get_posts', 'catalog_filters' );
    function catalog_filters( $query ) {
        if ( $query->is_main_query() && $query->post_type = 'product' ) {
            if(isset($_GET['onsale'])) {
                $meta_query = array(
                    'relation' => 'OR',
                    array( // Simple products type
                    'key' => '_sale_price',
                    'value' => 0,
                    'compare' => '>',
                    'type' => 'numeric'
                    ),
                    array( // Variable products type
                    'key' => '_min_variation_sale_price',
                    'value' => 0,
                    'compare' => '>',
                    'type' => 'numeric'
                    )
                ); $query->set('meta_query', $meta_query);
            }
            if(isset($_GET['bestsellers'])) {
                $meta_query     = array(
                array( 
                    'key'           => 'total_sales',
                    'value'         => 0,
                    'compare'       => '>',
                    'type'          => 'numeric'
                    )
                );
            }
        }
    
    return $query;
    }
    

提交回复
热议问题