Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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' => '<'
        ),
    )
); 
share|improve this question
 
If you need data comparison, you have to save the dates into multiple metas. Please refer to the Codex for the usage of add_post_meta. –  1fixdotio Feb 1 at 8:49
1  
Okay, I am already doing that. The income_dates custom field is holding the dates of recurring incomes and I thoight it would be better in an array otherwise the database might fill up pretty quickly. –  user537137 Feb 1 at 9:03
add comment

1 Answer

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'
         ),
     )
); 
share|improve this answer
 
Thanks for the reply and yeah that would work but I would prefer to keep the dates in a single entry so I've just fetched all posts and using an if statement to get the results I'm after –  user537137 Feb 2 at 7:12
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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