sinanisler logo

Scramble Randomize WordPress Posts publish dates within a maximum of 7 days

Add this code snippet to your functions.php or snippet plugin.

 

this will create a window to your dashboard. You will be able to randomize your post’s publish dates. within the last 7 days.

in default it is set to select the last 50 posts but you can change that number as you wish.

 

// Function to scramble publish dates within a maximum of 7 days
function randomize_date_times($posts) {
    $scrambled_posts = array();
    $current_time = current_time('timestamp');

    foreach ($posts as $post) {
        $publish_time = strtotime($post->post_date);
        $time_diff = $current_time - $publish_time;

        if ($time_diff > 0) {
            // Set a maximum range of 7 days (604800 seconds)
            $max_range = 604800;
            $random_offset = rand(-$max_range, 0);
            $scrambled_time = $publish_time + $random_offset;
            $post->post_date = date('Y-m-d H:i:s', $scrambled_time);
            $scrambled_posts[] = $post;
        } else {
            $scrambled_posts[] = $post;
        }
    }
    return $scrambled_posts;
}

// Function to scramble all posts
function scramble_all_posts() {
    $args = array(
        'posts_per_page' => 50, // change how many post you want to select
        'post_type' => 'post',
        'orderby' => 'date',
        'order' => 'DESC',
    );

    $all_posts = get_posts($args);
    $scrambled_posts = randomize_date_times($all_posts);

    foreach ($scrambled_posts as $scrambled_post) {
        wp_update_post($scrambled_post);
    }
}

// Callback function for the metabox
function randomize_date_times_callback() {
    echo '<div id="scramble-button-wrapper" class="wrap">
              <h2>Randomize Date Times</h2>
              <p>Click the button below to randomize the publish hours of posts within a maximum of 7 days.</p>
              <form method="post" action="">
                  <input type="hidden" name="randomize_action" value="randomize_posts">
                  <button type="submit" class="button button-primary">Randomize Date Times</button>
              </form>
          </div>';
}

// Add metabox to the dashboard
function add_randomize_date_times_metabox() {
    add_meta_box(
        'randomize_date_times',
        'Randomize Date Times',
        'randomize_date_times_callback',
        'dashboard',
        'side',
        'default'
    );
}
add_action('wp_dashboard_setup', 'add_randomize_date_times_metabox');

// Handle button click event
function randomize_button_click_handler() {
    if (isset($_POST['randomize_action']) && $_POST['randomize_action'] === 'randomize_posts') {
        scramble_all_posts();
        echo '<div class="notice notice-success is-dismissible">
                  <p>Post publish hours have been randomized within a maximum of 7 days.</p>
              </div>';
    }
}
add_action('admin_init', 'randomize_button_click_handler');

 

Leave the first comment