skip to Main Content

I’m trying to figure out a direct link to display all sale items in the shop. URLs can usually filter out specific attributes and queries, so I was hopeful that this would be possible. So far, no luck.

My result turns up: no products found. But there are indeed products on sale.

I’ve tried the following:

add_filter( 'woocommerce_product_query_meta_query', 'filter_on_sale_products', 20, 1 );
function filter_on_sale_products( $meta_query ){
    if( isset($_GET['onsale']) && $_GET['onsale'] ){
        $meta_query[] = array(
            'key' => '_sale_price',
            'value' => 0,
            'compare' => '>'
        );
    }
    return $meta_query;
}

This should return all sale items by URL: https://www.example.com/shop/?onsale=1

Any advice would be appreciated

2

Answers


  1. Your code contains some very minor errors.

    You can use the woocommerce_product_query action hook instead. This should suffice:

    function action_woocommerce_product_query( $q ) {
        if ( is_admin() ) return;
    
        // Isset & NOT empty
        if ( isset( $_GET['onsale'] ) ) {
            // Equal to 1
            if ( $_GET['onsale'] == 1 ) {
                //  Function that returns an array containing the IDs of the products that are on sale.
                $product_ids_on_sale = wc_get_product_ids_on_sale();
    
                $q->set( 'post__in', $product_ids_on_sale );
            }
        }
    }
    add_action( 'woocommerce_product_query', 'action_woocommerce_product_query', 10, 1 );
    
    Login or Signup to reply.
  2. check this link out

    $args = array(
        'post_type'      => 'product',
        'posts_per_page' => 8,
        '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'
            )
        )
    );
    
    $loop = new WP_Query( $args );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search