Where to register REST route to wordpress plugin endpoint Where to register REST route to wordpress plugin endpoint wordpress wordpress

Where to register REST route to wordpress plugin endpoint


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.