BIG
WordPress

How to enable CORS in WordPress?

BIG linden / Support Docs / How to enable CORS in WordPress?
Last edit: December 28, 2022
(4 weeks ago)

WordPress

How to enable CORS in WordPress?

Q:

The client is looking for information about customizing the Access-Control-Allow-Headers (CORS) property for their WordPress API.

Issue

How can I customize the Access-Control-Allow-Headers property for my WordPress API?

Possible solution

They can achieve this by setting up a header CORS function, enabling it using the rest_pre_serve_request filter, and allowing multiple origins if necessary. However, they should thoroughly test whatever policy they use before deploying it on their website in order to avoid any potential issues with functionality or security.

You can easily set whatever CORS policy you want either directly on your server, or via WordPress functions.

Below is a tutorial on how to customize the Access-Control-Allow-Headers property for your WordPress REST API via your theme’s functions.php file:

Be sure to thoroughly test whatever policy you end up using though, so you don’t inadvertently deliver a broken website to the client.

How to enable CORS in WordPress

Time needed: 3 minutes.

There are numerous options to enable CORS, but the easiest approach is to use a basic custom function. Instructions for how to enable CORS in WordPress are below:

  1. Use a custom function, fastest way to enable CORS in WordPress:


    function add_cors_http_header(){
    header(“Access-Control-Allow-Origin: *”);
    }
    add_action(‘init’,’add_cors_http_header’);

    Be sure not to use any combinations of these ( .htaccess, header.php, api.php, functions.php ) as it will cause redirect and/or critical errors.

  2. QA the site

    Be sure to QA client sites on 2 devices, at minimum (multiple networks are preferred).

Additional reading

  • This recent support thread about the necessity of CORS policies in the API and potential vulnerabilities
  • Very recent vulnerability submission using JSON and the API; typical cross-origin
  • Read about enabling CORS for Bitnami – probably not a package you’re working with on our network, but still very relevant information on the general topic of enabling CORS for WordPress
  • “CORs in Action” by Monsur Hossain – available from Simon & Schuster. “CORS in Action introduces Cross-Origin Resource Sharing (CORS) from both the server and the client perspective. It starts with the basics: how to make CORS requests and how to implement CORS on the server. It then explores key details such as performance, debugging, and security.”

More articles about WordPress

More articles related to .

Capabilities related to WordPress: