Where to register REST route to wordpress plugin endpoint

20.1k views Asked by At

Where must the registration function go? (register_rest_route())

  • Must it be in theme/child functions.php?
  • Or can it be in the plugin base php file? (e.g. \wp-content\plugins\example\example.php)

Is there any documentation that clarifies this?

It is not mentioned in the official documentation at: https://developer.wordpress.org/rest-api/extending-the-rest-api/routes-and-endpoints/

Similarly, where must the endpoint function be stored? The registration function only names it, without specifying its path.

For example, can you do like this:

  • Registration function call (register_rest_route) goes in main plugin file (e.g. \wp-content\plugins\example\example.php)
  • Endpoint function is in some other plugin file (e.g. \wp-content\plugins\example\sub-path-stuff\example-controller.php)

If so, how?

The following link appears to attempt this but does not specify these attributes (e.g. \wp-content\plugins\example\example.php)

1

There are 1 answers

4
Johnny Tee On BEST ANSWER

So register_rest_route goes inside "rest_api_init" action hook, and callbacks for routes can be defined in same file or in external one (then you can require it inside main file so you could add them to route/s). Here's an example:

Let's say you have a plugin "api-test", it's placed in: \wp-content\plugins\api-test and we'll add api-test.php as main plugin file (will be functional not oop for this example sake). Inside api-test.php you can have something like:

/**
 * @wordpress-plugin
 * Plugin Name: WP Rest api testing..
 */

/**
 * at_rest_testing_endpoint
 * @return WP_REST_Response
 */
function at_rest_testing_endpoint()
{
    return new WP_REST_Response('Howdy!!');
}

/**
 * at_rest_init
 */
function at_rest_init()
{
    // route url: domain.com/wp-json/$namespace/$route
    $namespace = 'api-test/v1';
    $route     = 'testing';

    register_rest_route($namespace, $route, array(
        'methods'   => WP_REST_Server::READABLE,
        'callback'  => 'at_rest_testing_endpoint'
    ));
}

add_action('rest_api_init', 'at_rest_init');

This is really simple example where everything's in the same file.