How to easily set post date & time to current date & time in WordPress?

If you need to edit date of a post, you can simply use the inbuilt feature of WordPress, but if you need to do it often for whatever reasons, the provided snippet will be useful for you.

Add the following snippet in your theme’s function.php. If it’s an theme that will probably get updated in future, create a child theme, activate it & add the code.

function tgg_checkbox_to_publish_metabox() {
    global $post;
    
    // Add a nonce for security purposes
    wp_nonce_field( 'custom_checkbox_nonce', 'custom_checkbox_nonce' );
    
    ?>
    <div class="misc-pub-section misc-pub-section-last">
        <label>
            <input type="checkbox" value="1" name="update_post_date" /> 
            Update to current time
        </label>
    </div>
    <?php
}
add_action( 'post_submitbox_misc_actions', 'tgg_checkbox_to_publish_metabox' );


function tgg_update_post_date_on_save( $post_id ) {
    // Check if our nonce is set and if it's valid.
    if ( ! isset( $_POST['custom_checkbox_nonce'] ) || ! wp_verify_nonce( $_POST['custom_checkbox_nonce'], 'custom_checkbox_nonce' ) ) {
        return;
    }

    // If this is an autosave, our form has not been submitted, so we don't want to do anything.
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    }

    // Check if checkbox is checked.
    if ( isset( $_POST['update_post_date'] ) && '1' === $_POST['update_post_date'] ) {
        // Remove the action to prevent infinite loop
        remove_action( 'save_post', 'update_post_date_on_save' );

        // Update the post date
        wp_update_post( array(
            'ID' => $post_id,
            'post_date' => current_time( 'mysql' ),
            'post_date_gmt' => current_time( 'mysql', 1 ),
        ));

        // Re-add the action
        add_action( 'save_post', 'update_post_date_on_save' );
    }
}
add_action( 'save_post', 'tgg_update_post_date_on_save' );

You should see this checkbox when you edit any post.

Leave a Reply

Your email address will not be published. Required fields are marked *