I tried to include this code in my plug-in php files as well as in functions.php
.
(In the end I would like it to be in the plug-in’s php file but I’m not yet sure if possible, that would probably be the topic of another question.)
It is a very basic method for now, I’m just trying to get a response with some content.
In both cases, I get a 404 response.
add_action( 'rest_api_init', function () {
register_rest_route( plugin_dir_url(__DIR__).'my-project/api/v1/form', '/action', array(
'methods' => 'GET, POST',
'callback' => 'api_method',
) );
});
function api_method($data) {
var_dump($data);
return 'API method end.';
}
And I tried to access URLs (in brower or with AJAX)
- http://my-domain.local/wp-content/plugins/my-project/api/v1/form
- http://my-domain.local/wp-content/plugins/my-project/api/v1/form/
- http://my-domain.local/wp-content/plugins/my-project/api/v1/form/get
- http://my-domain.local/wp-content/plugins/my-project/api/v1/form/get/
I guess I’m missing something.
2 s
Maybe start with just GET
. Your route looks weird as well. Try just:
register_rest_route('my-project/v1', '/action/', [
'methods' => WP_REST_Server::READABLE,
'callback' => 'api_method',
]);
And your callback is not returning a valid response. Let your callback look more like this:
$data = [ 'foo' => 'bar' ];
$response = new WP_REST_Response($data, 200);
// Set headers.
$response->set_headers([ 'Cache-Control' => 'must-revalidate, no-cache, no-store, private' ]);
return $response;
Finally you must combine wp-json
, the namespace my-project/v1
and your route action
to the URL you now can check for what you get:
https://my-domain.local/wp-json/my-project/v1/action