From 91c546d47a3fd8a04eaa5b624ae2b85784a50980 Mon Sep 17 00:00:00 2001 From: Aaron Jorbin Date: Thu, 2 May 2024 16:01:29 +0000 Subject: [PATCH] REST API: Return empty object when no fallback templates are found (wp/v2/templates/lookup) This prevents a number of php notices that are surfaced due to the endpoint being called on load of the post editor even when there are no templates. Props grantmkin, CookiesForDevo, britner, wildworks, jorbin. Fixes #60909. git-svn-id: https://develop.svn.wordpress.org/trunk@58079 602fd350-edb4-49c9-b593-d223f7449a82 --- .../class-wp-rest-templates-controller.php | 3 ++- .../tests/rest-api/wpRestTemplatesController.php | 13 +++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php b/src/wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php index 9eb64707aea07..1c2a7697c4ec0 100644 --- a/src/wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php +++ b/src/wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php @@ -165,7 +165,8 @@ public function get_template_fallback( $request ) { array_shift( $hierarchy ); } while ( ! empty( $hierarchy ) && empty( $fallback_template->content ) ); - $response = $this->prepare_item_for_response( $fallback_template, $request ); + // To maintain original behavior, return an empty object rather than a 404 error when no template is found. + $response = $fallback_template ? $this->prepare_item_for_response( $fallback_template, $request ) : new stdClass(); return rest_ensure_response( $response ); } diff --git a/tests/phpunit/tests/rest-api/wpRestTemplatesController.php b/tests/phpunit/tests/rest-api/wpRestTemplatesController.php index 50678a686d561..376daffee2989 100644 --- a/tests/phpunit/tests/rest-api/wpRestTemplatesController.php +++ b/tests/phpunit/tests/rest-api/wpRestTemplatesController.php @@ -909,6 +909,19 @@ public function test_get_template_fallback() { $this->assertSame( 'index', $response->get_data()['slug'], 'Should fallback to `index.html` when ignore_empty is `true`.' ); } + /** + * @ticket 60909 + * @covers WP_REST_Templates_Controller::get_template_fallback + */ + public function test_get_template_fallback_not_found() { + wp_set_current_user( self::$admin_id ); + $request = new WP_REST_Request( 'GET', '/wp/v2/templates/lookup' ); + $request->set_param( 'slug', 'not-found' ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + $this->assertEquals( new stdClass(), $data, 'Response should be an empty object when a fallback template is not found.' ); + } + /** * @ticket 57851 *