meta_query on a date range using an array of values

How can I do a query to return the post if the custom field array contains a date that is within the specified range?
The query below is basically what I am after but it does not work…

// the income_dates array looks like this
// a:3:{i:0;s:10:"2014-02-01";i:1;s:10:"2014-03-01";i:2;s:10:"2014-03-29";}

$today = date("Y-m-d");
$date1 = date("Y-m-d", strtotime($today . "-1 Month"));
$date2 = date("Y-m-d", strtotime($today . "+1 Month"));

$args = array(
    'post_type' => 'income',
    'meta_query' => array( 
        array(
            'key' => 'income_dates',
            'value' => $date1,
            'type'  => 'date',
            'compare' => '>'
        ),
        array(
            'key' => 'income_dates',
            'value' => $date2,
            'type'  => 'date',
            'compare' => '<'
        ),
    )
); 

Related posts

2 comments

  1. I needed to get post with type event and the custom field “date” later than today, this sample of code worked perfectly for me, I hope it helps to someone in a similar situation.

                $today = date("Y-m-d");
                $today1 = date("Ymd", strtotime("$today"));
                $custom_meta = array(
                    array(
                        'key' => 'data_de_inicio',
                        'value'=>$today1,
                        'compare'=>'>',
                        'type'=>'date',
                    ),
                );
                $query = new WP_Query(array(
                    'post_type'=>'event',
                    'showposts'=>'3',
                    'orderby'=>'meta_value',
                    'meta_key'=>'data_de_inicio',
                    'order'=>'asc',
                    'meta_query'=>$custom_meta,
                    )
                );
    
  2. I suggest don’t store the meta values as array because (I think) is not what you need. I think you really need to store each meta value individually with its own pair of key/value and not a single key with a serialized values. When done in this way, you can use the BETWEEN comparison:

    $today = date("Y-m-d");
    //'BETWEEN' comparison with 'type' date only works with dates in format YYYYMMDD.
    //See http://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters 
    $date1 = date("YYYYMMDD", strtotime($today . "-1 Month"));
    $date2 = date("YYYYMMDD", strtotime($today . "+1 Month"));
    
    $args = array(
        'post_type' => 'income',
        'meta_query' => array( 
         array(
             'key' => 'income_dates',
             'value' =>  array($date1,$date2),
             'type'  => 'date',
             'compare' => 'BETWEEN'
             ),
         )
    ); 
    

Comments are closed.