| CARVIEW |
Changeset 44568
- Timestamp:
- 01/11/2019 06:18:41 PM (7 years ago)
- Author:
- desrosj
- Message:
-
REST API: Encourage proper usage of
register_rest_route().
Calling
register_rest_route()too early in the loading process has the potential to cause some unintentional problems and pitfalls. Becauseregister_rest_route()callsrest_get_server()(which creates theWP_REST_Serverinstance), calling the function directly and/or beforerest_api_initshould be discouraged.
For example, if
register_rest_route ()is called oninit, the REST API server instance is set up (and all functions added torest_api_initand other related hooks are invoked), even though the current request may not be a REST request. Also, ifregister_rest_route()is called even earlier (say, in anmu-pluginfile), required endpoints may be missing since normal plugins have not yet been loaded and have not had a chance to register their own action hooks.
This adds a
_doing_it_wrong()notice the first timeregister_rest_route()is called beforerest_api_initin a request to encourage best practices for registering REST API routes.
Props kraftbj, desrosj, timothyblynjacobs.
Fixes #45265.
- Location:
- trunk
- Files:
-
- 2 edited
-
src/wp-includes/rest-api.php (modified) (2 diffs)
-
tests/phpunit/tests/rest-api.php (modified) (1 diff)
Legend:
- Unmodified
- Added
- Removed
-
trunk/src/wp-includes/rest-api.php
r44546 r44568 18 18 * Registers a REST API route. 19 19 * 20 * @since 4.4.0 20 * Note: Do not use before the {@see 'rest_api_init'} hook. 21 * 22 * @since 4.4.0 23 * @since 5.1.0 Added a _doing_it_wrong() notice when not called on or after the rest_api_init hook. 21 24 * 22 25 * @param string $namespace The first URL segment after core prefix. Should be unique to your package/plugin. … … 40 43 _doing_it_wrong( 'register_rest_route', __( 'Route must be specified.' ), '4.4.0' ); 41 44 return false; 45 } 46 47 if ( ! did_action( 'rest_api_init' ) ) { 48 _doing_it_wrong( 'register_rest_route', __( 'REST API routes must be registered on the rest_api_init action.' ), '5.1.0' ); 42 49 } 43 50 -
trunk/tests/phpunit/tests/rest-api.php
r44172 r44568 15 15 class Tests_REST_API extends WP_UnitTestCase { 16 16 public function setUp() { 17 parent::setUp(); 18 17 19 // Override the normal server with our spying server. 18 20 $GLOBALS['wp_rest_server'] = new Spy_REST_Server(); 19 parent::setUp();21 do_action( 'rest_api_init', $GLOBALS['wp_rest_server'] ); 20 22 } 21 23