Best Practice? Looper with custom meta date

Hi! I am building a grid based on a custom post type and sorting by a custom field… business as ususal. and is works great:

post_type=mec-events&orderby=meta_value&meta_key=mec_start_date&order=ASC&posts_per_page=4&date_query=mec_start_date

However, I need to only show events where the start date is greater than equal today and I do not think the query string can do that and the query builder only has options for using published date. I am assuming I need to do a meta query or the like, but before I dive in I was hoping for some guidance and best approach and practice?

Thank you!

1 Like

Hello Michael,

Thanks for reaching out.

Your query is like this:

$meta_query[] = array(
    'key'     => 'mec_start_date',
    'value'   => date('Ymd'),
    'compare' => '>=',
);

$query = array(
    'post_type'  => 'mec-events',
    'meta_key'   => 'mec_start_date',
    'orderby'    => 'meta_value',
    'order'      => 'ASC',
    'meta_query' => $meta_query
);

Using the @Kory’s solution from this article (Looper Query String: Featured Products), you should be getting this query string:

post_type=mec-events&meta_key=mec_start_date&orderby=meta_value&order=ASC&meta_query%5B0%5D%5Bkey%5D=mec_start_date&meta_query%5B0%5D%5Bvalue%5D=20210805&meta_query%5B0%5D%5Bcompare%5D=%3E%3D

where the “20210805” is the date of today. And to get the current, you will have to use the dynamic content date “{{dc:global:date format="Ymd"}}

Therefore the final query string would be like this:

post_type=mec-events&meta_key=mec_start_date&orderby=meta_value&order=ASC&meta_query%5B0%5D%5Bkey%5D=mec_start_date&meta_query%5B0%5D%5Bvalue%5D={{dc:global:date format="Ymd"}}&meta_query%5B0%5D%5Bcompare%5D=%3E%3D

Hope this explains your issue briefly.

This is a treasure trove. I was 60% there and no doubt that last 40% would hav totally eluded me.

Well I spun up a test page because this will come in useful in the future. My result being:

post_type=mec-events&meta_key=mec_start_date&orderby=meta_value&order=ASC&meta_query%5B0%5D%5Bkey%5D=mec_start_date&meta_query%5B0%5D%5Bvalue%5D={{dc:global:date format="Ymd"}}&meta_query%5B0%5D%5Bcompare%5D=%3E%3D

The above did not work. I went through the query string and it appears that it falls apart at the meta query.
So in case anyone is interested just specify the TYPE as DATE

$meta_query[] = array( 'key' => 'mec_start_date', 'value' => date('Ymd'), 'compare' => '>=', 'type' => 'DATE', );

Also, you can add poster per page (&posts_per_page=4) as well.

Ruenel… THANK YOU!!!

1 Like

Hi Michael,

Glad that you are able to find that and share it for others.

Thanks

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.