Skip to content

Instantly share code, notes, and snippets.

@rxnlabs
Last active June 27, 2023 20:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rxnlabs/f656ee6a754d364f0e21aba78eeca897 to your computer and use it in GitHub Desktop.
Save rxnlabs/f656ee6a754d364f0e21aba78eeca897 to your computer and use it in GitHub Desktop.
WordPress - Allow CORS headers for external sites. Allow external site to make an AJAX request against the WP site if you don't have access to the .htaccess file or your site is hosted on an NGINX server
<?php
/**
* Add CORS HTTP headers to the page request to allow the MTS curriculm site to make an AJAX request against the site
*
* Modify the HTTP headers that WordPress outputs before they are sent so we can add CORS headers to the request for things like an AJAX request
*
* @param array $headers The HTTP headers that WordPress is about to send
* @param WP $wp The current WordPress environment instance
*
* @return array The modified list of HTTP headers that we should send to the browser
*/
function add_cors_http_header_response( $headers, $wp ) {
$origin = get_http_origin();
$sites_to_allow_cors = [ 'https://site-one.com', 'https://site-two.com' ];
if ( ! empty( $origin ) ) {
foreach ( $sites_to_allow_cors as $maybe_origin ) {
if ( false !== strpos( $origin, $maybe_origin ) ) {
$headers['Access-Control-Allow-Origin'] = $origin;
$headers['Access-Control-Allow-Methods'] = 'GET'; // only allow GET requests
$headers['Access-Control-Allow-Credentials'] = 'true';
}
}
}
return $headers;
}
add_filter( 'wp_headers', 'add_cors_http_header_response', 1, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment