1

I need to find posts with a meta key that starts with the current year + the current month (i.e. 201502), but the actual value could also contain any day within that month (i.e. 20150214).

The really tricky part is that I'm trying to do this with ACF's Reapter and Date Picker fields. I've got it working to where it can return true if the I ask for posts containing a full date string (20150214), but I can't figure out how to do it for just the year and month.

Here's my current code:

// custom filter to replace '=' with 'LIKE'
function my_posts_where($where) {
    $where = str_replace("meta_key = 'show_times_%_date'", "meta_key LIKE 'show_times_%_date'", $where);
    return $where;
}
add_filter("posts_where", "my_posts_where");
// get results

$this_month = date("Ym") . "14"; // this doesn't work if I remove the . "14"
$the_query = new WP_Query(array(
    "numberposts" => -1,
    "post_type" => "plays_events",
    "meta_query" => array(
        array(
            "key"   => "show_times_%_date",
            "value" => $this_month,
        )
    ),
));

I'm really confused by the my_posts_where but, I just copied and modified it from this page.

Essentially it's the "value" option that I need to figure out how to say $this_month . $any_day.

Thanks.

2 Answers 2

1

I figured it out:

$the_query = new WP_Query(array(
    "numberposts" => -1,
    "post_type" => "plays_events",
    "meta_query" => array(
        array(
            "key"     => "show_times_%_date",
            "value"   => $this_month . "[0-9]{2}",
            "compare" => "REGEXP"
        )
    ),
));
0

I believe all you need to do here is remove the day from your $this_month parameter and use the LIKE comparison (with a trailing %) to query the value -

$this_month = date("Ym");
$the_query = new WP_Query(array(
    "numberposts" => -1,
    "post_type" => "plays_events",
    "meta_query" => array(
        array(
            "key"       => "show_times_%_date",
            "value"     => $this_month . "%",
            "compare"   => "LIKE"
        )
    ),
));

Check out the Custom Field Parameters section in the Class Reference for WP_Query

1
  • That doesn't appear to have worked, I suspect because of the filter I need to use to find sub-field values, but I'm not sure. Feb 16, 2015 at 15:58

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.