In this tutorial, you’ll learn how to query posts by date field using WordPress Advanced Custom Fields plugin.
If you’re familiar with querying posts in WordPress templates, in general, it will be straightforward.
Let’s create a new date field “Event start date”, which will have a slug “event_start_date” and assign it to posts only in the Events category.
Now, if we want to display only the future events in the templates we can simply do this.
<?php
$today = current_time('Ymd');
$posts = get_posts(array(
'posts_per_page' => -1,
'post_type' => 'post',
'meta_query' => array(
array(
'key' => 'event_start_date',
'compare' => '>=',
'value' => $today,
),
),
'meta_key' => 'event_start_date',
'orderby' => 'meta_value_num',
'order' => 'ASC'
));
if( $posts ): ?>
<?php foreach( $posts as $post ):
setup_postdata( $post );
?>
<?php include('inc/event.php'); ?>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
The code above will only show future events. Alternatively, you can change the comparison operand and show the past events or events that will happen today.
If you find this post useful, please let me know in the comments below.
Cheers,
Renat Galyamov
Want to share this with your friends?
👉renatello.com/wordpress-query-posts-by-date
PS: make sure you check other WordPress tutorials, e.g. my WordPress .gitignore config file, load Google Fonts via functions.php in WordPress and download my plugin that improves your WordPress SEO & Performance.