REST API: Restore global post state in WP_REST_Posts_Controller.Ensur…#11455
REST API: Restore global post state in WP_REST_Posts_Controller.Ensur…#11455liaisontw wants to merge 2 commits intoWordPress:trunkfrom
Conversation
|
The following accounts have interacted with this PR and/or linked issues. I will continue to update these lists as activity occurs. You can also manually ask me to refresh this list by adding the Core Committers: Use this line as a base for the props when committing in SVN: To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook. |
Test using WordPress PlaygroundThe changes in this pull request can previewed and tested using a WordPress Playground instance. WordPress Playground is an experimental project that creates a full WordPress instance entirely within the browser. Some things to be aware of
For more details about these limitations and more, check out the Limitations page in the WordPress Playground documentation. |
96d1b3f to
88cbb48
Compare
apermo
left a comment
There was a problem hiding this comment.
Other than the indentation on the phpdoc, looks good to me
…es that the global $post object is restored to its original state after calling setup_postdata() in prepare_item_for_response(). This fixes a regression where the global context could be 'polluted' during REST API requests.Fixes #43502.
88cbb48 to
3439f7a
Compare
This PR addresses a long-standing issue in WP_REST_Posts_Controller::prepare_item_for_response() where the global $post object was not restored after calling setup_postdata().
When the REST API processes post data, it temporarily modifies the global $post state to ensure core functions (like get_the_content()) work correctly. However, failing to reset this state leads to "global context pollution," especially when the REST API is called internally during a custom WP_Query loop or other custom development contexts.
Changes included in this PR:
Manual State Backup: Saves the original $GLOBALS['post'] before modification.
Robust Restoration: Ensures the global $post is restored to its original state (including null) in both the main execution path and the early-return path for HEAD requests.
Comprehensive Unit Tests: 1. Verified that the global $post is restored to its previous object after the API call.
2. Verified that the global $post is restored to null if it wasn't set before the call.
Trac ticket: https://core.trac.wordpress.org/ticket/43502
Use of AI Tools
AI assistance: Yes
Tool(s): Gemini
Model(s): Gemini 3 Flash
Used for: Identifying the core architectural issue (global state pollution vs. wp_reset_postdata limitations) and drafting the technical explanation for the PR description. The final implementation was verified against the latest Trac patch (#43502.6.diff) and local PHPUnit tests.