REST API: ignore empty templates.

Ignore empty templates when using the `/lookup` endpoint in the `WP_REST_Templates_Controller` class.

Props ramonopoly, jorgefilipecosta, spacedmonkey, youknowriad, mukesh27.
Fixes #58615.



git-svn-id: https://develop.svn.wordpress.org/trunk@56051 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Isabel Brison
2023-06-27 05:34:12 +00:00
parent 44a71b595e
commit a44e46b914
2 changed files with 17 additions and 3 deletions
@@ -150,14 +150,21 @@ class WP_REST_Templates_Controller extends WP_REST_Controller {
* 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 );
$hierarchy = get_template_hierarchy( $request['slug'], $request['is_custom'], $request['template_prefix'] );
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 );
}
@@ -837,5 +837,12 @@ class Tests_REST_WpRestTemplatesController extends WP_Test_REST_Controller_Testc
$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`.' );
}
}