0

I found this solution but it's now not working now (I am getting a fatal error), can anyone please update the code so its works with WordPress 6.1 (Original Post: Update existing post dates to random dates)

<?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 );
  }
}

I have a huge amount of posts, I think in this code trying to pull all posts at a time so if possible maybe we can add a batch system?

4
  • 1
    I don't see anything here that would be affected by any WordPress changes since it was written. What error are you getting? Jul 21, 2022 at 6:29
  • Hi, @JacobPeattie when I am activating WordPress just showing fatal error, no description. Maybe this plugin trying to pull all posts same time, if we can give a limit then maybe it will work.
    – Mi2
    Jul 21, 2022 at 7:23
  • @JacobPeattie do you know any CLI way to do samething?
    – Mi2
    Jul 21, 2022 at 7:35
  • Yes, this will crash your site if you have a lot of posts. Using a WP CLI custom command is a good idea. You can use the same function as the callback to WP_CLI::add_command
    – Paul
    Jul 21, 2022 at 10:09

0

Your Answer

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

Browse other questions tagged or ask your own question.