Creating a custom endpoint for a WordPress REST non-registering API

I followed some examples and it seems I can’t register the endpoint. I am creating a custom plugin and want to register a custom endpoint. Here is my code:

add_action( 'init', 'setup_init' );


function setup_init() {

   add_action( 'rest_api_init', 'wpc_register_wp_api_endpoints' );

   function wpc_register_wp_api_endpoints() {

    register_rest_route( 'setup', '/client/menu', array(
        'methods' => 'GET',
        'callback' => 'menu_setup',
    ));
}

   function menu_setup($request_data){
       return 'hello world';
   }
}

I visit mysite.com/setup/client/menu and I get a page error message. Then I check mysite.com/wp-json/wp/v2/ and I do not see that my route / endpoint is registered. My plugin is included. Am I doing something wrong?

+4
source share
1 answer

There is one small mistake in registering endpoints. Replace the line:

register_rest_route( 'setup', '/client/menu'

with:

register_rest_route( 'setup/client', '/menu'

The following is a complete snippet of your code:

add_action( 'init', 'setup_init' );


function setup_init() {

   add_action( 'rest_api_init', 'wpc_register_wp_api_endpoints' );

   function wpc_register_wp_api_endpoints() {

    register_rest_route( 'setup/client', '/menu', array(
        'methods' => 'GET',
        'callback' => 'menu_setup',
    ));
}

   function menu_setup($request_data){
       return 'hello world';
   }
}

, - , :)

0

Source: https://habr.com/ru/post/1668292/


All Articles