Allow Cross-Origin API Requests
Web browsers do not allow websites to make cross-origin requests (requests from one domain to another) unless the target website explicitly allows these types of requests.
As a result, if you intend for the REST API on your WordPress site to be publicly available for others to use, you will need to allow cross-origin requests. You can be explicit and only allow requests from a specific domain, or you can allow requests from any domain.
This is how you’d allow it for any external domain:
<?php
add_action( 'rest_api_init', function() {
remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
add_filter( 'rest_pre_serve_request', function( $value ) {
header( 'Access-Control-Allow-Origin: *' );
header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE' );
header( 'Access-Control-Allow-Credentials: true' );
return $value;
});
}, 12 );
To make this specific to a particular domain, just replace the *
with the domain.