I’m trying to display a list of posts in WordPress with dates that are equal to or greater than today – the purpose is to list out upcoming events.
Here’s the code I have right now:
// Get the current date
$current_date = date('M d, Y');
$current_date = strtotime( $current_date );
// Get the event date
$post_date = get_the_time('M d, Y');
$post_date = strtotime( $post_date );
query_posts(array('category_name' => 'events',
'meta_query' => array(
array(
'key' => $post_date,
'value'=> $current_date,
'compare'=>'>='
)
),
'showposts' => 4,
'orderby' => 'date',
'order' => ASC));
while (have_posts()) : the_post();
As you can see, I’m grabbing the current date and the date of the post. I know this code works, because I had it functioning mostly in the following format:
// Get the current date
$current_date = date('M d, Y');
$current_date = strtotime( $current_date );
query_posts(array('category_name' => 'events',
'showposts' => 4,
'orderby' => 'date',
'order' => ASC));
while (have_posts()) : the_post();
// Get the date
$post_date = get_the_time('M d, Y');
$post_date = strtotime( $post_date );
// If older than current date, don't show it
if( $post_date >= $current_date ):
But the problem with that is that it finds the posts, then compares them to the current date. So if I want to show 4 of my 10 posts, but 3 are hidden because they’re in the past, I’m actually only displaying 1 post here.
I need to compare to the current date then show 4 posts from the result of that calculation.
Any help is greatly appreciated. Thanks!
To do this you can use a
date_query
as part of yourquery_posts()
call (in place of themeta_query
).This will then eliminate the need to check the date of
Posts
once a query has been run, so you should always get the four that you are seeking.Note: I’d strongly recommend reviewing the
WP_Query
codex for further information as there are some very useful parameters in there. These can help you to further refine thePosts
that are returned and include the likes ofpost_type
,post_status
andcat
. Of course not all of these will be relevant to you in all situations (or possibly at all), but it’s still worth a read.Caution: Please be aware that
posts_per_page
replacedsome time ago.show_posts
Update
You mention in the comments that the above code is working, but only one
Post
is being retrieved. My initial thoughts are that this is caused by one of two things –Post
, and thus there are no more to show.LIMIT
portion.I suggest viewing the query that was passed to
MySQL
as soon as it is made. To do this, add the following line directly belowquery_posts($args)
and reload your page. –