It’s hard to tell what’s wrong without knowing what’s going on in your WP but here are some ideas:
Check the headers of those responses to see if CORS headers are present. As an example, when requesting https://test.frontity.io/wp-json/wp/v2/pages?_embed=true&slug=about-us
these are the headers I get:
I think this is the default behavior.
If those headers are not present then the code you added to functions.php
isn’t working. Why? I’d guess something is overriding those headers.
Try to see what filters are making use of that same hook in case one of them comes after yours and changes that. I simple test would be to add to your functions.php
something like this:
add_action( 'rest_api_init', function() {
global $wp_filter;
var_dump($wp_filter['rest_pre_serve_request']);
}, 99 );
This will print on the response’s body something like:
object(WP_Hook)#251 (5) {
["callbacks"]=>
array(1) {
[10]=>
array(2) {
["_oembed_rest_pre_serve_request"]=>
array(2) {
["function"]=>
string(30) "_oembed_rest_pre_serve_request"
["accepted_args"]=>
int(4)
}
["rest_send_cors_headers"]=>
array(2) {
["function"]=>
string(22) "rest_send_cors_headers"
["accepted_args"]=>
int(1)
}
}
}
["iterations":"WP_Hook":private]=>
array(0) {
}
["current_priority":"WP_Hook":private]=>
array(0) {
}
["nesting_level":"WP_Hook":private]=>
int(0)
["doing_action":"WP_Hook":private]=>
bool(false)
}
Where you can see the callbacks registered to act on that hook.
If everything looks fine there the overriding might be happening somewhere else.
You can also try to hook your code in functions.php
to rest_pre_echo_response
which I think is the last hook before the response is sent:
add_action('rest_api_init', 'my_prefix_wp_rest_allow_all_cors');
function my_prefix_wp_rest_allow_all_cors() {
add_filter( 'rest_pre_echo_response', function( $value ) {
header( 'Access-Control-Allow-Origin: *' );
header( 'Access-Control-Allow-Headers: *' );
header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE' );
header( 'Access-Control-Allow-Credentials: true' );
return $value;
});
}
Hope anything of this helps.