Recently all of my REST-API requests suddenly turned to return a 404 error, Every request (no matter custom endpoint or built-in).
Then I figured it’s because of permalink’s structure. /wp-json/
is not accessible under plain permalink, since there is simply no redirect rule available at the moment.
Is it possible to use the REST endpoints in this situation? Both custom and built-in.
Yes you can. Just add the rest_route
query parameter.
So
https://wordpress.org/wp-json/
would become
https://wordpress.org/?rest_route=/
Or https://wordpress.org/wp-json/wp/v2/
would become https://wordpress.org/?rest_route=/wp/v2
to give you a more complete example.
So you’re wondering how to decide which one to use? Worry no more, there’s a function for that: get_rest_url()
Another option is the fact that by default there is a <link>
in the header that gives you the API root.
<link rel="https://api.w.org/" href="https://wordpress.org/wp-json/" />
So in case you need to figure that out from client side JS just use something along the lines of
document.querySelectorAll('link[rel="https://api.w.org/"]')[0].getAttribute('href');
So basically you shouldn’t take the wp-json
part as given (and hardcode it) but always build it dynamically either using get_rest_url()
or the JS approach mentioned above.