Woocommerce query by price range and custom meta key

I’ve written a function to get products by price range. All works, but now I need add a extra meta key, that will be like 50 – 100 and featured, but code is not returning any products. What is wrong on this code?

    function product_price_filter_box($attr) {
    $limit = intval($attr['limit']);
    $min = intval($attr['min']);
    $max = intval($attr['max']);
    $query = array(
        'post_status' => 'publish',
        'post_type' => 'product',
        'posts_per_page' => $limit,
        'meta_query' => array(
            'relation'      => 'AND',
            array(
                'key' => '_price',
                'value' => array($min, $max),
                'compare' => 'BETWEEN',
                'type' => 'NUMERIC'
            ),
            array(
                'key'       => 'featured',
                'value'     => '1',
                'compare'   => '=',
            ),
        )
    );

    $wpquery = new WP_Query($query);
    while ( $wpquery->have_posts() ) : $wpquery->the_post(); global $product;
        wc_get_template_part( 'content', 'product' );
    endwhile;
    wp_reset_query();

}
add_shortcode( 'product_price_filter_box', 'product_price_filter_box' );

2 Answers
2

The featured product’s meta key is _featured, but you are using featured in your meta query. This will return no products, since the key doesn’t exist.

Also, as far as I know, the value of the key is yes, so your arguments should be like this:

array(
    'key'       => '_featured',
    'value'     => 'yes',
)

Another note, is to use the proper way to get the shortcode’s attribute. You can do so by using shortcode_atts() function. Here is the syntax for your case:

$atts = shortcode_atts(
    array(
        'limit' => '20',
        'min' => '1'
        'max' => '2'
    ), 
    $atts, 
    'product_price_filter_box' 
);

$limit = intval($atts['limit']);
$min = intval($atts['min']);
$max = intval($atts['max']);

You might want to limit the maximum posts a user can get. This can be done by using the min() function:

$limit = min(20, $limit);

And a final note. If you are using WP_Query, you should use wp_reset_postdata(); instead of wp_reset_query();, which is used after you use query_posts();.

Leave a Comment