Created
February 21, 2024 10:23
-
-
Save lucymtc/2f58dec4f3219b5554932b2d788c2a84 to your computer and use it in GitHub Desktop.
resolve CORS error headless WP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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