Created
May 7, 2019 14:49
-
-
Save lgedeon/ce872ee268c7d9da78abc218370319ea to your computer and use it in GitHub Desktop.
Save content as the second most recent post revision while preserving the most recent as matching the current content of the post.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Save history of content changes to post revision. | |
* | |
* @param integer $post_id Post ID. | |
* @param string $content Content. | |
* | |
* @return bool | |
*/ | |
function save_as_revision( $post_id, $content ) { | |
// Make sure this is not already a revision. | |
$post = get_post( $post_id ); | |
if ( ! $post ) { | |
return false; | |
} | |
// Get old revision if it exists. | |
$old_revision = false; | |
$revisions = wp_get_post_revisions( $post->ID ); | |
if ( $revisions ) { | |
// Find the last revision that is not an autosave. | |
foreach ( $revisions as $revision ) { | |
if ( false !== strpos( $revision->post_name, "{$revision->post_parent}-revision" ) ) { | |
$old_revision = $revision->ID; | |
break; | |
} | |
} | |
} | |
// Force WP to create a revision even though we haven't changed anything. | |
add_filter( 'wp_save_post_revision_check_for_changes', '__return_false' ); | |
$new_revision = wp_save_post_revision( $post->ID ); | |
// If there was no existing revision, use $new_revision and create a new $new_revision. | |
if ( ! $old_revision ) { | |
$old_revision = $new_revision; | |
$new_revision = wp_save_post_revision( $post->ID ); | |
} | |
if ( $old_revision && $new_revision ) { | |
return $this->update_content( $old_revision, $content ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment