Skip to content

Commit

Permalink
REST API: Return empty object when no fallback templates are found (w…
Browse files Browse the repository at this point in the history
…p/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
  • Loading branch information
aaronjorbin committed May 2, 2024
1 parent 73b7808 commit 91c546d
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -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 );
}
Expand Down
13 changes: 13 additions & 0 deletions tests/phpunit/tests/rest-api/wpRestTemplatesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*
Expand Down

1 comment on commit 91c546d

@joemaller
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this!

Please sign in to comment.