Meta query (with filter) to list posts *between* two dates

[ad_1]

I have a meta field (defined by the ACF plugin), with key event_date that stores a “date” in the post_meta table in the form: 20240515 (YYYYMMdd).

I’d like to use a shortcode such as the following to pull all posts with event_date between two dates:

[display-posts meta_key="event_date" meta_date_value_after="2024-01-01" meta_date_value_before="2024-06-01"]

To do this, I think I need to do something similar to the various event calendar filter examples, so I’ve got a skeleton filter that looks like this:

function atp_dps_event_date_between ( $args, $atts ) {
    
    // Ensure that all three parameters are in use and that meta_key is 'event_date'; 
    // else return the $args (no modifications necessary)
    if( ! ( isset( $atts['meta_key'] ) && $atts['meta_key'] == 'event_date'
            && isset( $atts['meta_date_value_after'] ) 
            && isset( $atts['meta_date_value_before'] ) ) )
        return $args;

    // what goes here?


    return $args;
}
add_filter( 'display_posts_shortcode_args', 'atp_dps_event_date_between', 10, 2 );

My problem, obviously, is that I don’t know how to build up the meta query itself, as I’m not quite sure how to do the date/string comparison, as well as the “double” query to handle before/after. It would seem to me to be something along these lines for a “after,” but then I don’t know how to add the “before.”

$meta_query = array(
    array(
      'key' => 'event_date',
      'value' => $atts['meta_date_value_after'],
      'compare' => '>=',
    )
  );

I’m going to work on this a bit more on my end, hopefully finding a solution that I can post here for others to use. But, if anyone can hop in whit a solution, that’d be awesome.

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer