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 d1854c5073e69..67d0f0c813ebb 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 @@ -150,14 +150,21 @@ public function register_routes() { * Returns the fallback template for the given slug. * * @since 6.1.0 + * @since 6.3.0 Ignore empty templates. * * @param WP_REST_Request $request The request instance. * @return WP_REST_Response|WP_Error */ public function get_template_fallback( $request ) { $hierarchy = get_template_hierarchy( $request['slug'], $request['is_custom'], $request['template_prefix'] ); - $fallback_template = resolve_block_template( $request['slug'], $hierarchy, '' ); - $response = $this->prepare_item_for_response( $fallback_template, $request ); + + do { + $fallback_template = resolve_block_template( $request['slug'], $hierarchy, '' ); + array_shift( $hierarchy ); + } while ( ! empty( $hierarchy ) && empty( $fallback_template->content ) ); + + $response = $this->prepare_item_for_response( $fallback_template, $request ); + return rest_ensure_response( $response ); } diff --git a/tests/phpunit/data/themedir1/block-theme/templates/tag.html b/tests/phpunit/data/themedir1/block-theme/templates/tag.html new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/tests/phpunit/tests/rest-api/wpRestTemplatesController.php b/tests/phpunit/tests/rest-api/wpRestTemplatesController.php index f6310a5e42765..7ab14e20be667 100644 --- a/tests/phpunit/tests/rest-api/wpRestTemplatesController.php +++ b/tests/phpunit/tests/rest-api/wpRestTemplatesController.php @@ -837,5 +837,12 @@ public function test_get_template_fallback() { $request->set_param( 'template_prefix', 'page' ); $response = rest_get_server()->dispatch( $request ); $this->assertSame( 'page', $response->get_data()['slug'], 'Should fallback to `page.html`.' ); + // Should fallback to `index.html`. + $request->set_param( 'slug', 'author' ); + $request->set_param( 'ignore_empty', true ); + $request->set_param( 'template_prefix', 'tag' ); + $request->set_param( 'is_custom', false ); + $response = rest_get_server()->dispatch( $request ); + $this->assertSame( 'index', $response->get_data()['slug'], 'Should fallback to `index.html` when ignore_empty is `true`.' ); } }