Replace WordPress's "any origin" CORS headers with a list of domains allowed to call your REST API from a browser.
add_action( 'rest_api_init', function (): void {
remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
add_filter( 'rest_pre_serve_request', function ( $served ) {
$allowed = [
home_url(),
'https://app.example.com',
];
$allowed = array_map( fn ( string $url ): string => untrailingslashit( set_url_scheme( $url, 'https' ) ), $allowed );
$origin = get_http_origin();
if ( $origin && in_array( untrailingslashit( set_url_scheme( $origin, 'https' ) ), $allowed, true ) ) {
header( 'Access-Control-Allow-Origin: ' . esc_url_raw( $origin ) );
header( 'Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS' );
header( 'Access-Control-Allow-Credentials: true' );
header( 'Access-Control-Allow-Headers: Authorization, X-WP-Nonce, Content-Disposition, Content-MD5, Content-Type' );
header( 'Vary: Origin', false );
}
return $served;
} );
}, 15 );
Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.
WordPress answers REST API requests from any website with CORS headers that allow the browser to read the response. For public data that’s fine, but if your API serves logged-in users to a separate app, you may want to limit which sites can call it from the browser.
WordPress sends CORS headers through rest_send_cors_headers(), which echoes back whatever Origin the browser sends. The snippet removes that and adds its own version, which only sends Access-Control-Allow-Origin when the origin is in your list.
Origins are compared on scheme and host, with trailing slashes removed. Vary: Origin tells caches that the response depends on who asked.
From an allowed site’s browser console, run fetch('https://yoursite.com/wp-json/'). It should work. From any other site it should fail with a CORS error.