0

I have code that successfully returns product within a price range. However, I need to also filter by a product attribute called 'size'.

So I should get all products of a certain size between the given price range.

My code works for the price range part, but I can't work out the correct way to add the size part.

Here's my code:

$params = array(
    'posts_per_page' => 20,
    'post_type' => array('product', 'product_variation'),
    'meta_query' => array(
        'relation' => 'AND',
        array(
            array(
                'key' => '_price',
                'value' => $_POST['product_price_min'],
                'compare' => '>=',
                'type' => 'NUMERIC'
            ),
            array(
                'key' => '_price',
                'value' => $_POST['product_price_max'],
                'compare' => '<=',
                'type' => 'NUMERIC'
            )

        ),
        array(
            array(
                            'taxonomy'        => 'pa_size',
                            'field'           => 'slug',
                            'terms'           =>  $_POST['size'],
                            'operator'        => 'IN',

            )
        )
    )
);


$products = new WP_Query($params);
1
1

Your mixing up your meta query and tax query. try this:

$params = array(
    'posts_per_page' => 20,
    'post_type' => array('product', 'product_variation'),
    'meta_query' => array(
        array(
            'key' => '_price',
            'value' => $_POST['product_price_min'],
            'compare' => '>=',
            'type' => 'NUMERIC'
        ),
        array(
            'key' => '_price',
            'value' => $_POST['product_price_max'],
            'compare' => '<=',
            'type' => 'NUMERIC'
        ),
    ),
    'tax_query' => array(
        array(
        'taxonomy'        => 'pa_size',
        'field'           => 'slug',
        'terms'           =>  $_POST['size'],
        'operator'        => 'IN',
        )
    )
);


$products = new WP_Query($params);
1
  • Thanks, this works perfectly! – benhen31 Mar 21 '19 at 19:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.