Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress REST Api: add_action( 'rest_api_init', callback) does not call the callback

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.

  • I'm using docker for development
  • No errors are being thrown

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?

like image 759
Bram Janssen Avatar asked Nov 07 '25 17:11

Bram Janssen


2 Answers

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.

enter image description here

like image 78
Bram Janssen Avatar answered Nov 09 '25 08:11

Bram Janssen


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
like image 32
Dario Fumagalli Avatar answered Nov 09 '25 07:11

Dario Fumagalli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!