WordPress.org

Make WordPress Core


Ignore:
Timestamp:
01/11/2019 06:18:41 PM (21 months 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. Because register_rest_route() calls rest_get_server() (which creates the WP_REST_Server instance), calling the function directly and/or before rest_api_init should be discouraged.

For example, if register_rest_route () is called on init, the REST API server instance is set up (and all functions added to rest_api_init and other related hooks are invoked), even though the current request may not be a REST request. Also, if register_rest_route() is called even earlier (say, in an mu-plugin file), 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 time register_rest_route() is called before rest_api_init in a request to encourage best practices for registering REST API routes.

Props kraftbj, desrosj, timothyblynjacobs.
Fixes #45265.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/tests/phpunit/tests/rest-api.php

    r44172 r44568  
    1515class Tests_REST_API extends WP_UnitTestCase {
    1616    public function setUp() {
     17        parent::setUp();
     18
    1719        // Override the normal server with our spying server.
    1820        $GLOBALS['wp_rest_server'] = new Spy_REST_Server();
    19         parent::setUp();
     21        do_action( 'rest_api_init', $GLOBALS['wp_rest_server'] );
    2022    }
    2123
Note: See TracChangeset for help on using the changeset viewer.