0

I'm having issues adding a custom REST API route to Wordpress. Using my own plugin, i've registered the route as followed:

add_action( 'rest_api_init', function() {
  register_rest_route( $namespace, 'handler_mijnenergie', array(
    'methods'   => '\WP_REST_Server::CREATABLE ',
    'callback'  => [ $this, 'handle_energie_data' ]
  ), false );
} );

When calling the namespace "/wp-json/watz/v1" I get a correct response in Postman that the route is shown. enter image description here

However, when i try to access the route request directly, i get thrown a 404 error. So far I've tried:

  • Rewriting the permalinks
  • Using standard Wordpress .htaccess
  • Disabling plugins
  • Changing method/namespace & request
  • Testing other plugin routes like Yoast or Contact Form 7 (they work)

Any idea what could be causing the issue here and what I need to alter to get this working?

0

It's because of how you've defined the accepted methods:

'methods'   => '\WP_REST_Server::CREATABLE ',

You shouldn't have quotes around it. WP_REST_Server::CREATABLE is a string that equals 'POST', but by putting quotes around it you're literally setting the method as '\WP_REST_Server::CREATABLE', which is not a valid HTTP method. You can see this in the response to the namespace endpoint.

Set it like this:

'methods' => WP_REST_Server::CREATABLE

Or, if your file is using a PHP namespace, like this:

'methods' => \WP_REST_Server::CREATABLE

Or add this to the top of the file:

use WP_REST_Server;

Then make sure that when you're accessing the route directly, that you're using the correct method. If you're using WP_REST_Server::CREATABLE then the endpoint will only respond to POST requests, so GET requests will return a 404, which includes when you access it via the browser.

  • Thanks for the feedback, that worked like a charm! I learned something again today :) – BroodjeBE Oct 9 at 8:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.