Skip to content

Instantly share code, notes, and snippets.

@lucymtc
Created February 21, 2024 10:23
Show Gist options
  • Select an option

  • Save lucymtc/2f58dec4f3219b5554932b2d788c2a84 to your computer and use it in GitHub Desktop.

Select an option

Save lucymtc/2f58dec4f3219b5554932b2d788c2a84 to your computer and use it in GitHub Desktop.
resolve CORS error headless WP
WP headers api for for POST from localhost:3000:
<?php
// init hook as will be global. send_headers hook doesn't work on rest api.
add_action( 'init', [ $this, 'security_headers' ] );
// DEBUG_MODE_CLIENT_URL = http://localhost:3000
public function security_headers() {
if ( defined( 'DEBUG_MODE_CLIENT_URL' ) ) {
header("Access-Control-Allow-Origin: " . DEBUG_MODE_CLIENT_URL);
header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Accept");
}
}
?>
OR To load some page from WP in iframe in FE:
<?php
add_action( 'send_headers', [ $this, 'security_headers' ] );
/**
* Add Content-Security-Policy header to embed page in iframe from the client app.
*
* @return void
*/
function security_headers() {
if ( defined( 'HEADLESS_MODE_CLIENT_URL' ) && is_specific_page_request() ) {
$subdomain = str_replace( 'https://', 'https://*.', HEADLESS_MODE_CLIENT_URL );
$non_www = str_replace( 'https://www.', 'https://', HEADLESS_MODE_CLIENT_URL );
header( 'Content-Security-Policy: frame-ancestors ' . HEADLESS_MODE_CLIENT_URL . ' ' . $subdomain . ' ' . $non_www );
}
}
function is_specific_page_request () {
$parsed_url = wp_parse_url( $_SERVER['REQUEST_URI'] );
$path = trim( $parsed_url['path'], '/' );
return 'specific-path' === $path;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment