0

I have 1700 Motivational Updates + Write ups imported to WordPress.

The problem is they are all published on the same date.

I'd ideally like for them to be published once per day.

I researched a lot and found this.

$date1       = date( $date_format, strtotime("-1 year", time()) );
$date2       = date( $date_format, time() );
$post_type   = 'post'; // post, page, product or some other custom post type

// Get all the posts
$posts = get_posts( array( 
        'numberposts' => -1, // get ALL posts
        'post_status' => 'any', // published, pending, draft, future, trash
        'post_type'   => $post_type 
  ));

foreach( $posts as $post ) {

  //* Generate a random post dates
  $random_date = mt_rand( strtotime( $date1 ), strtotime($date2) );

  //* 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 );

}

This setup works great, if am trying to randomize the post dates. However, it sometimes sets 2 or even 5 posts in the same day.

Is there someway to have it such that the published_date is set to 1 per day, the time of the day can be randomized.

Any help is greatly appreciated.

1
  • Note that 1700 posts into 365 days automatically means that there will be multiple posts per day. If they're fully randomized, there should be ~ 1700/365 = 4.65 posts each day. Alternately, you'll need 4.65 years' worth of dates for the posts to be 1 a day.
    – Pat J
    Jun 27, 2022 at 20:46

1 Answer 1

1

You could start from today and just work backwards, one day at a time:

$start_hour = 8;

$end_hour = 17;

$date = new DateTime;

foreach ( $posts as $post ) {
    $time = sprintf(
        /* Left-pad time values with zeros to two digits */
        '%02d:%02d:%02d',
        /* Random hour between start and end */
        rand( $start_hour, $end_hour ),
        /* Random minutes */
        rand( 0, 59 ),
        /* Random seconds */
        rand( 0, 59 )
    );

    $post_date = $date->format( 'Y-m-d' );

    wp_update_post( array(
        'ID'            => $post->ID,
        'post_date'     => "$post_date $time",
        'post_date_gmt' => null,
    ));

    // Move date 1 day back
    $date->modify( '-1 day' );
}

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.

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