Reputation: 2742
I am following this tutorial to create custom end points to WP-API .
I am always getting this error on hitting /wp-json/custom-plugin/v2/get-all-post-ids/ on postman to test :
{
"code": "rest_no_route",
"message": "No route was found matching
the URL and request method ",
"data": {
"status": 404
}
}
I have created a custom-plugin.php file in /plugins/custom-plugin/ directory .
<?php
if ( ! defined( 'ABSPATH' ) ) exit;
add_action( 'rest_api_init', 'dt_register_api_hooks' );
function dt_register_api_hooks() {
register_rest_route( 'custom-plugin/v2', '/get-all-post-ids/', array(
'methods' => 'GET',
'callback' => 'dt_get_all_post_ids',
)
);
}
// Return all post IDs
function dt_get_all_post_ids() {
if ( false === ( $all_post_ids = get_transient( 'dt_all_post_ids' ) ) ) {
$all_post_ids = get_posts( array(
'numberposts' => -1,
'post_type' => 'post',
'fields' => 'ids',
) );
// cache for 2 hours
set_transient( 'dt_all_post_ids', $all_post_ids, 60*60*2 );
}
return $all_post_ids;
}
?>
Upvotes: 6
Views: 26944
Reputation: 10701
For a very similar problem, while I was designing an API in WordPress, I also got the same "code": "rest_no_route",...
error on some websites and not on other ones. I traced it back to the fact that POST requests were transformed into GET requests so they weren't recognized by my plugin.
The conversion from POST to GET was made before WordPress even started. I was able to pinpoint the problem and solve it by adding the following header, as explained in details here:
headers: { 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8' }
Upvotes: 2
Reputation: 11990
Ensure your callback to add_action( 'rest_api_init', 'dt_register_api_hooks' );
is being run.
In my case, my callback was not being called because I was using add_action('rest_api_init', ...)
too late; the action had already fired. As in, my call to register_rest_route()
never even happened.
Upvotes: 3