WordPress already has a default URL for jQuery-WordPress application calls and it’s well known as the ajaxurl
. However, there are cases wherein one would need to enable Cross-Origin Resource Sharing (CORS) on it such that any hostname will be able to access using it.
My current solutions is by adding a line in /wp-includes/http.php
with:
@header( 'Access-Control-Allow-Origin: *' );
Such that it will be:
http.php
...
function send_origin_headers() {
$origin = get_http_origin();
@header( 'Access-Control-Allow-Origin: *' );
if ( is_allowed_http_origin( $origin ) ) {
@header( 'Access-Control-Allow-Origin: ' . $origin );
@header( 'Access-Control-Allow-Credentials: true' );
if ( 'OPTIONS' === $_SERVER['REQUEST_METHOD'] )
exit;
return $origin;
}
if ( 'OPTIONS' === $_SERVER['REQUEST_METHOD'] ) {
status_header( 403 );
exit;
}
return false;
}
...
It works but editing the WordPress core is not a good solution.
Is there a better way to enable CORS for the ajaxurl
?
Warning
This topic contains security vulnerabilities when actually implementing it on a wordpress installation.
Note
This question was posted during the era of WordPress 4.3. When the WordPress 4.4 was released with the new feature WordPress REST API, enabling CORS no longer became necessary and instead just use the rest_api_init
hook to add custom REST endpoints.