0

I have found a code here that will randomize the date of all posts to a random date. Here is the code that someone has posted:

<?php
/**
 * Plugin Name: WPSE 259750 Random Dates
 * Description: On activation, change the dates of all posts to random dates
 */

//* We want to do this only once, so add hook to plugin activation
register_activation_hook( __FILE__ , 'wpse_259750_activation' );
function wpse_259750_activation() {

  //* Get all the posts
  $posts = get_posts( array( 'numberposts' => -1, 'post_status' => 'any' ) );
  foreach( $posts as $post ) {

    //* Generate a random date between January 1st, 2015 and now
    $random_date = mt_rand( strtotime( '1 January 2015' ), time() );
    $date_format = 'Y-m-d H:i:s';

    //* Format the date that WordPress likes
    $post_date = date( $date_format, $random_date );

    //* We only want to update the post date
    $update = array(
      'ID' => $post->ID,
      'post_date' => $post_date,
      'post_date_gmt' => null,
    );

    //* Update the post
    wp_update_post( $update );
  }
}

How would you do the same, but only randomize the time without randomizing the date of the post. So, the posts should keep the same date they currently have, but only randomize the time of the day they were posted.

I tried changing the post_date to post_time and changing the random_date to time() only. Then of course changing the date_format to 'H:i:s' however it did nothing.

0

This is the part that is responsible for random date:

//* Generate a random date between January 1st, 2015 and now
$random_date = mt_rand( strtotime( '1 January 2015' ), time() );

So you need to change it. And if you want to randomize only the time part, then this is one way to achieve that:

$random_date = strtotime( date( 'Y-m-d 00:00:00', strtotime($post->post_date) ) ) + mt_rand(0, 24*60*60); 

This line will:

  • take the date of post
  • get only day part of it
  • concert it to time
  • add random number of seconds to it

So it will randomize the time of publication.

  • This code does exactly what I've asked. Thank you so much for your prompt answer. – SpiritFly Jul 9 at 14:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.