How to enable CORS in WordPress
To set up Cross-Origin Resource Sharing (CORS) on your WordPress website, see below.
Time needed: 3 minutes.
There are numerous options to enable CORS, but the easiest approach is to use a basic custom function. Instructions for how to enable CORS in WordPress.
- Use a custom function, fastest way to enable CORS in WordPress:
function add_cors_http_header(){
header(“Access-Control-Allow-Origin: *”);
}
add_action(‘init’,’add_cors_http_header’);
Be sure not to use any combinations of these ( .htaccess, header.php, api.php, functions.php ) as it will cause redirect and/or critical errors. - QA the site
Be sure to QA client sites on 2 devices, at minimum (multiple networks are preferred).
Developer preferred method for allowing multiple origins
It sounds like your use case is that you want to be able to connect a couple different data sources and enable them to talk to one another, without opening the door to the entire world.
If that’s the case, and you want to Allow Multiple Origins on your CORS policy for the WordPress API, this custom function should do the trick, with no plugins or other tools necessary.
function initCors( $value ) {
$origin = get_http_origin();
$allowed_origins = [ 'site1.example.com', 'site2.example.com', 'localhost:3000' ];
if ( $origin && in_array( $origin, $allowed_origins ) ) {
header( 'Access-Control-Allow-Origin: ' . esc_url_raw( $origin ) );
header( 'Access-Control-Allow-Methods: GET' );
header( 'Access-Control-Allow-Credentials: true' );
}
return $value;
}
This code is a variation of the custom functions offered by Ruben Leija on his blog post ‘How to enable CORS on your WordPress REST API’.