0

I tried to create new custom rest API endpoint inside my theme function.php file. I also tried inside the plugins folder but it's not worked for me.

This is how I write the function on function.php

function register_our_custom_api_routes() {
register_rest_route( 'custom/v1', '/endpoint/', array(
        'methods'  => WP_REST_Server::READABLE,
        'callback' => 'our_custom_callback_function',
    )
);}

Below sample body of the response, I found it from this article but it's not worked for me.

function our_custom_callback_function(  ) {
  $data = [ 'foo' => 'bar' ];
  $response = new WP_REST_Response($data, 200);

  $response->set_headers([ 'Cache-Control' => 'must-revalidate, no-cache, no-store, private' ]);
  return $response;}

And finally I add

add_action( 'rest_api_init', 'register_our_custom_api_routes' );

It keeps getting me rest_no_route, 404 error when I try to access http://localhost/shopper/wp-json/custom/v1/endpoint

Are there any changes need to be done on .htaccess file side?

  • Oh no!. It's not an issue with the Wordpress REST API. It's an issue with the theme. Switching to the twentynineteen theme did the trick. Thanks everyone. – Chamith Kanchana May 5 at 6:40

Your Answer

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

Browse other questions tagged or ask your own question.