0

I want to change the date of publication of my already published posts to random dates within the range starting from 2015 till today.

How to do this in WordPress using CODE.

1
  • Why do you post the question like this here when there is nothing to do with WordPress?
    – Max Yudin
    Commented Mar 11, 2017 at 22:09

1 Answer 1

2

Question

How to change the post date to a randomly generated date?

Answer

This is fairly straightforward. What I did was to create a plugin that upon activation get all the posts, loops through them, generates a random date, and updates the post with that date.

<?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 );
  }
}
1
  • Tried on test website and worked! if i want another time range should I change this line: $random_date = mt_rand( strtotime( '1 January 2015' ), time() ); ? Great plugin you should add some basic settings and add in wordpress plugins repository... tnx!
    – Anty
    Commented Mar 13, 2017 at 13:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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