Problem:
I'm trying to register a custom endpoint for a Wordpress plugin. The problem I face is that when I call the add_action('rest_api_init', callback), the callback function is not being called. In that callback function lives the "register_rest_route()" method, which in it's turn is not being called and I am unable to register any custom endpoints.
Code:
public function register()
{
$this->setup_init();
}
public function setup_init()
{
var_dump('print1');
add_action('rest_api_init', array($this, 'register_custom_endpoints'));
}
public function register_custom_endpoints()
{
var_dump('print2');
die();
register_rest_route('test', '/test', array(
'methods' => 'GET',
'callback' => 'menu_setup',
));
}
Question:
The code reaches the "var_dump('print1')", but the the "var_dump('print2')" is never reached. Am I missing something here?
After trying many options I found out that changing: "Setting -> permalinks -> common settings" to anything else then the option "Plain" solved the issue. The callback method is now being reached, and my custom endpoints are being registered.

Reading your question and self-answer, you are using "Plain permalinks".
You wonder why it doesn't work.
Here's the answer, from the official WordPress documentation.
Basically, when you use plain permalinks you revert to a classic website with a lot of URL parameters. When using REST, your calls will need to be translated into that system in order for them to work.
Here's a simple example:
Imagine you want to get the blog post with id = 123.
With pretty permalinks, you'd call:
https://example.com/wp-json/wp/v2/posts/123
With plain permalinks, you have to call:
https://example.com/?rest_route=/wp/v2/posts/123
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With