Skip to main content

Updating post data on status transition

You might be tempted to set the WP_Post properties (but this is an action), or use wp_update_post() but there is some hard-coded behaviour in wp_insert_post() that might affect your data.

So it's better to emulate wp_publish_post().

function action_on_future_to_publish( $post ) {
	global $wpdb;

	if ( ! wp_is_post_revision( $post ) ) {
		// Update via the database to bypass wp_insert_post resetting the dates.
        // @see wp_publish_post()
		$data = [
			'post_modified'     => $post->post_date,
			'post_modified_gmt' => $post->post_date_gmt,
		];
		$wpdb->update( $wpdb->posts, $data, [ 'ID' => $post->ID ] );

		// After bypassing the WP caches, refresh the cache.
		clean_post_cache( $post->ID );
	}
}
add_action( 'future_to_publish', 'action_on_future_to_publish', 10, 1 );