we develop communication with weLaika Advertising

WP tricks: posts to the future

Tags: wordpress, trick, add_action, add_filter, hook
Filippo Gangi Dino -
Filippogangidino

In a recent WordPress work, I had to publish, with an external PHP script, a lot of posts with wpinsertpost() function. These posts had a non common feature: the ‘poststatus’ was ‘publish’ and the ‘postdate’ was in the future.

Normally, in WordPress, the posts with a date in the future have ‘post_status’ ‘future’ but, in this case, I couldn’t set it because the wordpress query shows in the frontend only published posts.

So the problem is that they don’t appear in any query because the WordPress query shows only posts with present date or before.

The solution

Add in your functions.php in the theme folder, or in hooks.php if you use Wordless, this function:

1
2
3
4
5
function show_posts_to_the_future($where = '') {
  $cut = "AND post_date <= '". date('Y-m-d', strtotime('now')) ."'";
  $where = str_replace($cut, "", $where);
  return $where;
}

removing the “WHERE post_date” condition into the query.

If you want a specific range in the future you can add this line:

1
$where .= " AND post_date < '" . date('Y-m-d', strtotime('+365 days')) . "'";

So you must override (in the same position) another function that launches the filter hooked by specific event:

1
2
3
function show_future($query) {
  add_filter('posts_where', 'show_posts_to_the_future');
}

For example, if you want to limit this query you can add an if condition before the addfilter. In my case it was only for backend and for a specific posttype:

1
if (is_admin() && ($query-&gt;query['post_type'] == 'book')){}

Now we must add an hook with an add_action():

1
add_action(pre_get_posts, show_future);

This action hooks all queries.

So you can view the Posts to the Future!