WordPress hacking: display only future posts
Force WordPress to only display posts dated in the future.
I recently inherited a WordPress site which uses a future posts plugin to allow you to publish posts with dates in the future.
This is great and a very simple solution for sites that list events but don't need complex calendar functionality. However, it had no way of automatically removing events listings which were now in the past and was showing a list of two year old events on the day I inherited it.
I'm a coder, therefore lazy, there's no way I'm removing posts manually, there's far too much chance of me messing up and forgetting to remove one at the right moment.
The quick and dirty simple and recommended solution to displaying future posts, or posts in any specified date range, is to set up a new WP_Query()
(via the recommended get_posts()
route) using the date or relative date (e.g. today or 30 days ago) you want to start from as one of the $args
something like this:
$args = array(
'order' => 'ASC',
'date_query' => array( 'after' => '-1 days' ));
$i=0;
$posts = get_posts($args);
if ($posts) : foreach ($posts as $post) : setup_postdata($post);
// code to display the post
This will display the event up-to and including the date that it's on, then it will magically disappear. Neat huh?
Comments powered by Talkyard.