Skip to content

Instantly share code, notes, and snippets.

@miya0001
Last active January 31, 2023 07:42
Show Gist options
  • Save miya0001/d6508b9ba52df5aedc78fca186ff6088 to your computer and use it in GitHub Desktop.
Save miya0001/d6508b9ba52df5aedc78fca186ff6088 to your computer and use it in GitHub Desktop.
CORS for the WordPress REST API
<?php
function my_customize_rest_cors() {
remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
add_filter( 'rest_pre_serve_request', function( $value ) {
header( 'Access-Control-Allow-Origin: *' );
header( 'Access-Control-Allow-Methods: GET' );
header( 'Access-Control-Allow-Credentials: true' );
header( 'Access-Control-Expose-Headers: Link', false );
return $value;
} );
}
add_action( 'rest_api_init', 'my_customize_rest_cors', 15 );
@JurajVajda
Copy link

how to use this file, where should i add it ?

@castilloedwin
Copy link

castilloedwin commented Jun 13, 2018

This header is also necessary.

header( 'Access-Control-Allow-Headers: X-Requested-With' );

@manoharkumarsingh
Copy link

function my_customize_rest_cors() {
remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
add_filter( 'rest_pre_serve_request', function( $value ) {
header( 'Access-Control-Allow-Origin: *' );
header( 'Access-Control-Allow-Methods: GET' );
header( 'Access-Control-Allow-Credentials: true' );
header( 'Access-Control-Expose-Headers: Link', false );
return $value;
} );
}
add_action( 'rest_api_init', 'my_customize_rest_cors', 15 );

Where i have to put this code

@saimunhossain
Copy link

where should I put this code?

@yuriitaran
Copy link

where should I put this code?

In functions.php

@JaakkoKarhu
Copy link

JaakkoKarhu commented Jan 11, 2019

For me this does not work, it just adds one more origin

I posted a question with more details to Stack Overflow

@ovidiojosearteaga
Copy link

Hi, the code worked for me. I put the code in a custom plugin for a specific WordPress project. Thanks.

@m1m1s1ku
Copy link

Thanks !! Works perfectly well with Wordpress latest !

@a-barbieri
Copy link

@ntnbst
Copy link

ntnbst commented Mar 19, 2020

Thanks, It worked 👍

@federicolucca
Copy link

Thanks, after 2 crazy day you save me

@mtrabelsi
Copy link

does it has something to do with WooCommerce ? it seems not

@m1m1s1ku
Copy link

@mtrabelsi What is your point there? This is to add the missing CORS headers to WP-json, in short, yes it can be linked to WooCommerce, depending on your use.

@jayllellis
Copy link

You are a lifesaver! Thank you!

@eikito
Copy link

eikito commented Oct 9, 2020

Hi, I have a problem with several Access-Control-Allow headers additionally to already existing one (highlighted in orange in attached Screenshot). Could this my_customize_rest_cors function help to solve my problem?

Access-Control-Allow-headers-additionally-to-already-existing-ones

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment