Нет описания

class-revisions-migrator.php 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /**
  3. * Duplicate Post class to migrate revisions from the Rewrite & Republish copy to the original post.
  4. *
  5. * @package Duplicate_Post
  6. * @since 4.0
  7. */
  8. namespace Yoast\WP\Duplicate_Post;
  9. /**
  10. * Represents the Revisions Migrator class.
  11. */
  12. class Revisions_Migrator {
  13. /**
  14. * Adds hooks to integrate with the Post Republisher class.
  15. *
  16. * @return void
  17. */
  18. public function register_hooks() {
  19. \add_action( 'duplicate_post_after_rewriting', [ $this, 'migrate_revisions' ], 10, 2 );
  20. }
  21. /**
  22. * Updates the revisions of the Rewrite & Republish copy to make them revisions of the original.
  23. *
  24. * It mimics the behaviour of wp_save_post_revision() in wp-includes/revision.php
  25. * by deleting the revisions (except autosaves) exceeding the maximum allowed number.
  26. *
  27. * @param int $copy_id The copy's ID.
  28. * @param int $original_id The post's ID.
  29. *
  30. * @return void
  31. */
  32. public function migrate_revisions( $copy_id, $original_id ) {
  33. $copy = \get_post( $copy_id );
  34. $original_post = \get_post( $original_id );
  35. if ( \is_null( $copy ) || \is_null( $original_post ) || ! \wp_revisions_enabled( $original_post ) ) {
  36. return;
  37. }
  38. $copy_revisions = \wp_get_post_revisions( $copy );
  39. foreach ( $copy_revisions as $revision ) {
  40. $revision->post_parent = $original_post->ID;
  41. $revision->post_name = "$original_post->ID-revision-v1";
  42. \wp_update_post( $revision );
  43. }
  44. $revisions_to_keep = \wp_revisions_to_keep( $original_post );
  45. if ( $revisions_to_keep < 0 ) {
  46. return;
  47. }
  48. $revisions = \wp_get_post_revisions( $original_post, [ 'order' => 'ASC' ] );
  49. $delete = \count( $revisions ) - $revisions_to_keep;
  50. if ( $delete < 1 ) {
  51. return;
  52. }
  53. $revisions = \array_slice( $revisions, 0, $delete );
  54. for ( $i = 0; isset( $revisions[ $i ] ); $i ++ ) {
  55. if ( \strpos( $revisions[ $i ]->post_name, 'autosave' ) !== false ) {
  56. continue;
  57. }
  58. \wp_delete_post_revision( $revisions[ $i ]->ID );
  59. }
  60. }
  61. }