0

The following code works in my theme's functions.php file but not in my plugin's main/entry file:

/** Allow cross origin resource access
 */
function add_cors_http_header(){
  header("Access-Control-Allow-Origin: *");
}
add_action('init','add_cors_http_header');

If put into the main plugin file I see this:

Access to XMLHttpRequest at 'http://localhost/
wptest2/wp-admin/admin-ajax.php' 
from origin 'http://localhost:8080' 
has been blocked by CORS policy: 
No 'Access-Control-Allow-Origin' header 
is present on the requested resource.

I need to setup CORS using my plugin files only so users won't have to make custom mods, is there any way to accomplish this?

Also tried in the plugin entry file (and failed):

function add_allowed_origins(array $origins = []) {
  $origins[] = 'http://localhost:8080';
  return $origins;
}
add_filter('allowed_http_origins', 'add_allowed_origins');

.

function add_cors_http_header() {
  header("Access-Control-Allow-Origin: *");
}
add_action('send_headers', 'add_cors_http_header');

1 Answer 1

1

Try using send_headers action hook instead of init. It should work.

add_action( 'send_headers', 'add_cors_http_header' );

function add_cors_http_header()
{
    header("Access-Control-Allow-Origin: *");
}
2
  • Thank you, still doesn't work unfortunately. This is after removing the code from the theme's functions.php and copy/pasting your code in the plugin's entry file
    – Sean D
    Commented Jul 12, 2019 at 20:57
  • I added the above code to the plugin file and all server responses contain a header with the value I insert. I do not know what may be the cause of other results for you.
    – nmr
    Commented Jul 12, 2019 at 21:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.