Search code examples
phpwordpresscorswordpress-rest-api

Enable CORS in wordpress api


I want a clean way to enable CORS for my wordpress backend. Many posts suggest to just add the header to the api's code but editing the wordpress core is a no-go and wouldn't work for my setup anyway as I'm using docker.

I've tried writing a plugin like so:

add_filter( 'wp_headers', array( 'send_cors_headers' ), 11, 1 );
function send_cors_headers( $headers ) {
        $headers['Access-Control-Allow-Origin'] = '*';
    return $headers;
}

But it just seems to do nothing at all, as I'm still getting the following error:

Failed to load http://localhost/wp-json/wp/v2/posts: Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.

Solution

  • Your client-side JavaScript is attempting to set an Access-Control-Allow-Origin header on the request.

    This makes no sense since it is a response header, not a request header.

    This is triggering a preflighted request, but your server-side code is only set up to handle simple requests.

    Fix the client-side JS.