Anton Putau
Anton Putau

Reputation: 762

rest_api_init event not fired

I am trying to run custom plugin on wp 4.7.4 . Below is my simple plugin

add_action( 'rest_api_init', 'register_routes');


function register_routes() {
   register_rest_route( 'taxonomy-manager/v1', '/taxonomies/(P<taxonomy_type>[a-zA-Z]+)', array(
   'methods' => 'GET',
   'callback' => 'get_or_insert'
  ) );
} 

function get_or_insert( WP_REST_Request $request ) {

   $parameters = $request->get_params();

   return $parameters;

}

When I request wp-json endpoint I see no plugin route there. Plugin was successfully activated. Have I missed something ? Does above plugin (or similar one based on rest_api_init event) works for anybody else ? Thanks.

Upvotes: 23

Views: 18534

Answers (5)

Ian Elvister
Ian Elvister

Reputation: 405

Check if your plugin is activated, it won't fire if it's not activated.

Upvotes: -1

Flimm
Flimm

Reputation: 151117

In my case, the callback was actually a private method. I had to change it to a public method to get everything to work:

class Example {
    function __construct() {
        add_action( 'rest_api_init', [ $this, 'example_method' ] );
    }

    public function example_method() {
        /* This will not work if the method is private! */
        /* ... */
    }
}
new Example();

On one installation, the method being private caused an error with a stack trace, but on another installation, the private method was simply not called and no errors were generated. I'm still not sure why one machine reacted one way and not the other, both had WP_DEBUG and WP_DEBUG_LOG set to true.

Upvotes: 1

Shakeel Ahmed
Shakeel Ahmed

Reputation: 1858

I got solution, You need to use wp-json with your URL... like https://yourdomain.com/wp-json/namespace/and-so-on/

Then it will work. I was missing wp-json in URL.

Upvotes: 10

Gnanasekaran Loganathan
Gnanasekaran Loganathan

Reputation: 1108

Refer below check list,
1. Change your permalink as a pretty permalink and check.
2. Check your .htacess file (it should be writable when you save permalink structure it re-writable by wp).
3. Check Auth.
4. Check below custom endpoint creation method,

add_action( 'rest_api_init', function () {
  register_rest_route( 'myplugin/v1', '/author/(?P<id>\d+)', array(
    'methods' => 'GET',
    'callback' => 'my_awesome_func',
  ) );
} );

REF : https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/

Upvotes: 10

Dharmesh Hadiyal
Dharmesh Hadiyal

Reputation: 729

Using the latest build I'm not seeing the rest_api_init action being fired. Looks like this code in the plugin.php is always empty and returns, never allowing the rest_api_init action to be fired:

if ( empty( $GLOBALS['wp']->query_vars['rest_route'] ) ) {
    return;
}

Upvotes: 0

Related Questions