How to Use compare => between for Dates in meta_query WordPress
You can also use meta_query
to check if a custom field is between two dates.
The most important thing you have to keep in mind is that your date format should be like YYYY-MM-DD
or YYYY/MM/DD
or something like that (year goes first, then month, then day, then time if you need it too). Check how it is stored in database – if it is stored in another format, for example days go first, then filtering won’t work for you until you change dates presence in database.
array( 'key' => 'sale_day', 'value' => array( '2018-01-01', '2018-01-09' ), 'compare' => 'BETWEEN' )
If the date is stored in UNIX time, example: 1543391233
, everything became super simple:
array( 'key' => 'sale_day', 'value' => array( strtotime('2018-01-01'), strtotime('2018-01-09') ), 'type' => 'numeric', 'compare' => 'BETWEEN' )
Multiple meta queries – get posts by multiple pairs of keys and values
Now I will show you how to combine posts by several (two or more) custom field values. First of all let me introduce you relation
parameter which can accept two vaues – OR
or AND
(default).
// the 'color' is 'white' AND the 'price' is more than 2000 and less than 4000 $rd_query = new WP_Query( array( 'meta_query' => array( 'relation' => 'AND', // both of below conditions must match array( 'key' => 'show_on_homepage', 'value' => 'on' ), array( 'relation' => 'OR', // only 'color' OR 'price' must match array( 'key' => 'color', 'value' => 'white' ), array( 'key' => 'price', 'value' => array( 2000, 4000 ), 'type' => 'numeric', 'compare' => 'BETWEEN' ) ) ) ) );
As you can see, in meta_query
above we used multiple relation
.