| 771 | |
| 772 | /** |
| 773 | * Create a revision when the autosave content is significantly different. |
| 774 | * |
| 775 | * If the autosave content is significantly different from the current post or the previous autosave, |
| 776 | * create a revision from the old data. |
| 777 | * |
| 778 | * @since 5.0.0 |
| 779 | * |
| 780 | * @param WP_Post $post The current post or the previous autosave revision. |
| 781 | * @param array $autosave_data The autosave data. |
| 782 | */ |
| 783 | function wp_create_revision_for_autosave( $post, $autosave_data ) { |
| 784 | |
| 785 | if ( ! wp_revisions_enabled( $post ) ) { |
| 786 | return; |
| 787 | } |
| 788 | |
| 789 | $post_data = get_object_vars( $post ); |
| 790 | |
| 791 | if ( $post_data['post_type'] === 'revision' ) { |
| 792 | // If the old post is a revision, need to merge it with the actual post. |
| 793 | $parent_post = $this->get_parent( $post_data['post_parent'] ); |
| 794 | foreach ( array_keys( _wp_post_revision_fields( $parent_post ) ) as $field ) { |
| 795 | if ( isset( $post_data[ $field ] ) ) { |
| 796 | $parent_post->$field = $post_data[ $field ]; |
| 797 | } |
| 798 | } |
| 799 | $post_data = get_object_vars( $parent_post ); |
| 800 | } |
| 801 | |
| 802 | $old_length = strlen( $post_data['post_content'] ); |
| 803 | |
| 804 | if ( $old_length > 1000 ) { |
| 805 | $difference = 250; |
| 806 | } elseif ( $old_length > 500 ) { |
| 807 | $difference = (int) $old_length * 0.2; |
| 808 | } elseif ( $old_length > 50 ) { |
| 809 | $difference = (int) $old_length * 0.3; |
| 810 | } else { |
| 811 | $difference = (int) $old_length * 0.5; |
| 812 | } |
| 813 | |
| 814 | $size_diff = strlen( $autosave_data['post_content'] ) - $old_length; |
| 815 | $create_revision = absint( $size_diff ) > $difference; |
| 816 | |
| 817 | /** |
| 818 | * Filter whether a revision is created when an autosave is made via the REST API. |
| 819 | * |
| 820 | * @since 5.0.0 |
| 821 | * |
| 822 | * @param bool $create_revision Create a revision? |
| 823 | * @param array $post_data The current post data. |
| 824 | * @param int $size_diff The calculated autosave difference. |
| 825 | */ |
| 826 | if ( apply_filters( 'wp_create_revision_for_autosave', $create_revision, $post_data, $size_diff ) ) { |
| 827 | _wp_put_post_revision( $post_data ); |
| 828 | } |
| 829 | } |