REST API: Avoid undefined property warning when creating a post with a slug#12404
REST API: Avoid undefined property warning when creating a post with a slug#12404abhishekrijal wants to merge 1 commit into
Conversation
…th a slug. `WP_REST_Posts_Controller::create_item()` passed `$prepared_post->id` (lowercase) to `wp_unique_post_slug()`. That property is never set on the stdClass built by `prepare_item_for_database()`, which only assigns the uppercase `ID`, and only on the update path. On create, `$prepared_post->id` is therefore always undefined, so on PHP 8+ creating a draft/pending post with a slug emitted "Warning: Undefined property: stdClass::$id". Pass the post ID defensively (0 for a new post), matching the `! empty( $prepared_post->ID )` guard used elsewhere in the controller, and add a regression test. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
|
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. |
Trac ticket
Trac ticket: https://core.trac.wordpress.org/ticket/XXXXX
Problem
WP_REST_Posts_Controller::create_item()passes$prepared_post->id(lowercase) towp_unique_post_slug():$prepared_postis a freshstdClassfromprepare_item_for_database(), which only ever assigns$prepared_post->ID(uppercase), and only on the update path. On create, neitheridnorIDisset, so
$prepared_post->idis an undefined property. Every other reference to the id in this filealready uses
->ID.E_NOTICE, coerced tonull→0(the correct value for a new post).E_WARNING"Undefined property: stdClass::$id" on every matching request.This fires on
POST /wp/v2/postswhen the request includes aslugand adraft/pendingstatus(common from the block editor), and is noisy in error loggers such as Sentry.
Fix
Pass the post ID defensively —
0for a brand-new post — matching the! empty( $prepared_post->ID )guard already used elsewhere in the controller:
Testing
Adds
test_create_draft_with_slug_does_not_emit_undefined_property_warning()totests/phpunit/tests/rest-api/rest-posts-controller.php, which creates a draft with an explicit slugand asserts (a) a 201 with the expected unique slug and (b) no
Undefined property: stdClass::$idwarning is emitted during dispatch.