How to prevent posts from being published too close to each other?

Here is a very rough block of code that should get you started. What it does is look for the most recent “future” or “publish” post and if that value is less than 1 hour different from the latest scheduled post, it schedules the current post to one hour plus the “most recent” time found.

function force_time_between_posts_wpse_104677($data, $postarr) {
  global $wpdb;
  if (empty($postarr['ID'])) return $data;

  $latest = $wpdb->get_var("
    SELECT post_date
    FROM {$wpdb->posts} 
    WHERE post_status IN('future','publish') 
    AND post_type="post" 
    AND ID != {$postarr['ID']}
    ORDER BY post_date DESC
    LIMIT 1");
  $distance = 60; // post publication spacing in minutes
  $latest = strtotime($latest);
  $current = strtotime($data['post_date']);

  if ($latest < $current) {
    $diff = $current - $latest;
  } else { 
    $diff = 0;
  }

  if ($diff >= 0 && $diff < ($distance * 60)) {
    $new_date = $latest + ($distance * 60);
    $date = date('Y-m-d H:i:s',$new_date);
    $date_gmt = get_gmt_from_date($date);
    $data['post_date'] = $date;
    $data['post_date_gmt'] = $date_gmt;
    $data['post_status'] = 'future';
  }
  return $data;
}
add_action('wp_insert_post_data','force_time_between_posts_wpse_104677',1,2);

This does in fact force the post scheduling, and if there is already a future post the next one will be scheduled after that already scheduled post. That means that it could potentially schedule posts far into the future.

You may want to exempt certain roles from this post scheduling, or require it only for a single role, just to help keep things manageable.

Leave a Comment