Skip to content

Commit c6952ed

Browse files
committed
Move wp_save_post_revision to wp_after_insert_post
When it runs on `post_updated` it's too early for the parent post to have had its meta saved. This works in both Gutenberg and the classic editor and a core ticket will be opened. props to @peterwilsoncc for the help
1 parent ef0514d commit c6952ed

File tree

1 file changed

+19
-6
lines changed

1 file changed

+19
-6
lines changed

revision-notes.php

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,15 @@ public function init() {
2424
add_action( 'post_submitbox_misc_actions', array( $this, 'edit_field' ) );
2525
add_action( 'save_post', array( $this, 'save_post' ), 10, 2 );
2626

27+
// As of 5.6, revisions are created too early for REST requests
28+
// so move the revision saving to after the post is fully inserted including meta.
29+
// This is fine for the classic editor too.
30+
// For future-proofing and compat, check to make sure it's hooked on already.
31+
if ( has_action( 'post_updated', 'wp_save_post_revision' ) ) {
32+
remove_action( 'post_updated', 'wp_save_post_revision', 10, 1 );
33+
add_action( 'wp_after_insert_post', array( $this, 'maybe_save_revision' ), 10, 3 );
34+
}
35+
2736
add_filter( 'wp_prepare_revision_for_js', array( $this, 'wp_prepare_revision_for_js' ), 10, 2 );
2837
add_filter( 'wp_post_revision_title_expanded', array( $this, 'wp_post_revision_title_expanded' ), 10, 2 );
2938

@@ -42,11 +51,11 @@ public function init() {
4251

4352
add_action( 'enqueue_block_editor_assets', array( $this, 'block_editor_assets' ) );
4453

45-
register_meta( 'post', 'revision_note', [
54+
register_meta( 'post', 'revision_note', array(
4655
'type' => 'string',
4756
'single' => true,
4857
'show_in_rest' => true,
49-
] );
58+
) );
5059
}
5160

5261
public function edit_field() {
@@ -105,17 +114,21 @@ public function save_post( $post_id, $post ) {
105114
// This relies on the revision being saved after the parent as specified by core!
106115
$parent = wp_is_post_revision( $post );
107116
$note = get_post_meta( $parent, 'revision_note', true );
108-
$test = get_post_meta( $parent, 'test', true );
109117

110118
if ( ! empty( $note ) ) {
111119
update_metadata( 'post', $post->ID, 'revision_note', wp_slash( $note ) );
112-
update_metadata( 'post', $post->ID, 'test', wp_slash( $test ) );
113120
}
114-
} else {
115-
update_metadata( 'post', $post->ID, 'test', $post->post_content );
116121
}
117122
}
118123

124+
public function maybe_save_revision( $post_id, $post, $update ) {
125+
if ( ! $update ) {
126+
return;
127+
}
128+
129+
wp_save_post_revision( $post_id );
130+
}
131+
119132
public function wp_prepare_revision_for_js( $data, $revision ) {
120133

121134
$note = esc_html( get_metadata( 'post', $revision->ID, 'revision_note', true ) );

0 commit comments

Comments
 (0)