Fix Gutenberg saving authors after PHP save post hooks have already run #1127
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
Currently, when editing a post in Gutenberg, the author terms are not saved to the post itself until after the editor has finished saving:
Co-Authors-Plus/src/index.js
Lines 39 to 48 in 14725a6
This creates issues when we have PHP methods hooked into any of the actions related to post saving and publishing (like save_post, post_status_transition, etc), as those hooks have already ran once the authors are saved, so the PHP code does not have access to the correct / up to date author terms for the post.
See issues: #1024 & #1053
To reproduce this, add a hook on save_post with 9999 priority and then do wp_get_post_terms( $post_id, 'author'). If the post hadn't been saved before, that will return empty. If it has been saved, but the authors have been edited since save, it will return outdated info.
My suggested PR is to add the author terms in the post at the same time as the React data store is updated, here:
https://github.com/carosioa/Co-Authors-Plus/blob/37dccd11c057d92646c569b3fb6ece55f169594c/src/components/co-authors/index.jsx#L102-L118
Then you can totally remove the subscribe action that is making api calls to add the authors and the state of the post in WordPress will always match with the Coauthors box.
I did have to add each author term ID to the API response for the search box so it that was easily accessible in React. Not sure if there is a better place for looking that up than here:
https://github.com/carosioa/Co-Authors-Plus/blob/37dccd11c057d92646c569b3fb6ece55f169594c/php/class-coauthors-endpoint.php#L210-L224
Deploy Notes
No new dependencies.
Steps to Test