1

Quick question: I would like to retrieve some pages/posts with a meta value inside a range, eg) $min<$meta_value<$max

for ordinary $meta_value there was a way to get pages/posts like this:

$args = array(
    'meta_key' => $key,
    'meta_value' => $meta_value, //$min<$meta_value<$max
    'post_type' => 'page',
    'post_status' => 'publish',
...
);
$pages = get_pages( $args );

What is the best solution? should I first get them all and check them in an if condition or should I use $wpdb->get_results($sql,OBJECT) or is there a better way?

From SQL we have:

SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2; 

Does the WP_query class have a method to use the BETWEEN keyword inside a query?

1
  • 1
    I fixed the code blocks, I would note that this kind of query will be expensive/slow
    – Tom J Nowell
    Commented Aug 4, 2021 at 16:51

1 Answer 1

1

In this situation you will want to use the meta_query parameter, an example:

$args = array(
    'post_type'   => 'page',
    'post_status' => 'publish',
    'meta_query'  => array(
        array(
            'key'     => $key,
            'value'   => array($min, $max),
            'compare' => 'BETWEEN',
        ),
    ),
);

$query = new WP_Query( $args );

The possible values for for the 'compare' key are:

  • "="
  • "!="
  • ">"
  • ">="
  • "<"
  • "<="
  • "LIKE"
  • "NOT LIKE"
  • "IN"
  • "NOT IN"
  • "BETWEEN"
  • "NOT BETWEEN"
  • "EXISTS" (only in WP >= 3.5)
  • "NOT EXISTS" (only in WP >= 3.5)
  • "REGEXP" (only in WP >= 3.7)
  • "NOT REGEXP" (only in WP >= 3.7)
  • "RLIKE" (only in WP >= 3.7)

Default value is "=".

Useful reading:

3
  • Oh, thanks. That's exactly what I was looking for. Commented Aug 4, 2021 at 16:45
  • 1
    @MartinSpinoza if this is the answer to your question can you mark it as the accepted answer so that Adam gets their reputation points? Otherwise the site will keep suggesting this question as needing an answer. It's the big check mark under the voting controls
    – Tom J Nowell
    Commented Aug 4, 2021 at 16:52
  • 1
    @TomJNowell Thanks. I did. Great community, I didn't expect to find my answer this soon. I wish I had more reputation to upvote this answer. Commented Aug 4, 2021 at 16:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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