meta_query all posts between to ages

I’m trying to query posts for a specific age range. For example I have a post with an age range from 5 – 10. If I use the following code I get a result when I search for ages >= 5 and 10:

$meta_query = array(
        'key'     => '_age_from',
        'value'   => sanitize_text_field( $_REQUEST['age_from'] ),
        'compare' => '>=',
        'type'    => 'NUMERIC'
    );

$meta_query = array(
        'key'     => '_age_to',
        'value'   => sanitize_text_field( $_REQUEST['age_to'] ),
        'compare' => '<=',
        'type'    => 'NUMERIC'
    );

But I also want to get results when I search for ages from 6 – 9 for example. I think this SQL-Query should do the trick but I’m currently not able to query this in wordpress:

WHERE (6 BETWEEN _age_from AND _age_to) AND (9 BETWEEN _age_from AND _age_to)

Could anybody help me out whit this? Would be awesome!

1 Answer
1

you can write like for this.

'meta_query' => array(                  
   array(
      'key'     => '_age_from',
    'value'   => sanitize_text_field( $_REQUEST['age_from'] ),
    'compare' => '>=',
    'type'    => 'NUMERIC'
    ),
   array(
    'key'     => '_age_to',
    'value'   => sanitize_text_field( $_REQUEST['age_to'] ),
    'compare' => '<=',
    'type'    => 'NUMERIC'
   )
);

Leave a Comment