Backed by Awesome Motive.
Learn more on our Seahawk Blog.

How to Fix CORS Error in WordPress?

Written By: author image Regina Patil
author image Regina Patil
Hey there! I'm Regina, an SEO Content Writer at Seahawk. My role involves writing various content formats, including website content, SEO articles, and in-depth blog posts.
Reviewed By: Ahana Datta
reviewer image Ahana Datta
fix-cors-error-in-wordpress

If you run a website, encountering errors is inevitable, and one such issue, though not among the common WordPress errors, is the CORS error. This error arises when your WordPress site attempts to access resources from a different origin (domain, protocol, or port), and the server hosting those resources does not permit it. 

Resolving CORS errors is crucial as they can disrupt essential functions like API calls, font loading, and AJAX requests, negatively impacting your site’s performance and user experience. Thus, this guide provides an overview of the steps you can undertake to identify and fix CORS errors in WordPress, ensuring your website remains functional and user-friendly.

What Is CORS (Cross-Origin Resource Sharing) Error?

Cross-Origin Resource Sharing (CORS) is a security feature that is implemented by web browsers to prevent malicious websites from accessing sensitive information on other sites without permission. It works by checking if the server hosting the resource includes specific headers that grant permission for cross-origin requests. 

cors-policy

A CORS error occurs when a web page tries to access resources from a different domain, protocol, or port, but the server does not allow it.

Typical scenarios where CORS errors occur in WordPress include:

  • Fetching External API Data: When your WordPress site tries to get data from an external API, a CORS error can occur if the API server does not allow your site to access its resources.
  • Loading Fonts from Another Domain: If you use custom fonts hosted on a different domain, you might encounter CORS errors if the font server doesn’t permit your site to load these fonts.
  • Using a CDN for Static Assets: When images, CSS, or JavaScript files are served from a CDN, CORS errors can arise if the CDN server does not have the correct headers to allow your site to access these files.
  • Making AJAX Requests: If your WordPress site makes AJAX requests to a custom REST API endpoint on a different subdomain, CORS errors can occur if the API server does not explicitly permit these requests.
  • Embedding Third-Party Widgets: Lastly, embedding widgets from other domains using iframes can lead to CORS errors if the widget server doesn’t allow cross-origin access.

Say Goodbye to Errors with a 24/7 WordPress Support Plan

No matter if it’s a CORS error or any other WordPress issue, our dedicated support team is here to help you around the clock.

How CORS Errors Affect Website Functionality and User Experience?

CORS errors can block crucial functionalities on your site, such as loading external data, custom fonts, or scripts. As a result, your site may not display correctly or fully function, leading to a poor user experience.

For example, features relying on external APIs might fail, custom fonts might not load, or interactive elements using AJAX could break.

Therefore, resolving CORS errors is essential to ensure your website runs smoothly and provides a seamless experience for users.

Identifying CORS Errors in WordPress

By following these steps, you can easily identify CORS errors in your WordPress site.

Check the Browser Console: Open your browser’s developer tools (by pressing F12 or right-clicking on the page and selecting “Inspect”). Go to the “Console” tab to see any error messages.

chrome-browser-cors-error

In the console, look for messages that mention “CORS policy” or “Cross-Origin Resource Sharing.” These messages will usually state that a resource has been blocked due to CORS.

In the developer tools, switch to the “Network” tab and reload the page.

  • Look for any requests marked in red, indicating they have failed.
  • Click on these requests to see more details about the error, including CORS-related issues.

Review API Response Headers: When working with APIs, inspect the response headers in the “Network” tab. Check if the “Access-Control-Allow-Origin” header is present and correctly configured.

Check Plugin Settings: If you are using plugins that interact with external resources, review their settings and documentation to ensure they handle CORS correctly.

Use Online Tools: Utilize online tools like CORS Checker to test if the external resources you are trying to access are properly configured to allow cross-origin requests.

Read about: Tips to Fix WordPress Updating and Publishing Failed Errors

Examples of CORS Errors in WordPress and Steps to Fix It

Here are some common scenarios where CORS errors arise in WordPress and simple steps to fix them.

Example 1: Fetching External API Data

Your WordPress site tries to get data from an external API, but fails.

Error Message:

Access to fetch at ‘https://api.example.com/data’ from origin ‘https://yourwordpresssite.com’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

Method to Fix: Modify the .htaccess file in your WordPress root directory:

<IfModule mod_headers.c>

    Header set Access-Control-Allow-Origin "*"

</IfModule>

This tells the server to allow any site to access the resource.

Example 2: Loading Fonts from Another Domain

Your WordPress site uses custom fonts hosted on a different domain, but they do not load.

Error Message:

Access to font at ‘https://fonts.example.com/font.woff2’ from origin ‘https://yourwordpresssite.com’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

Method to Fix: Add the following code to your theme’s functions.php file:

function add_cors_headers() {
    header("Access-Control-Allow-Origin: *");
}
add_action('init', 'add_cors_headers');

This helps add the required CORS headers to all responses.

Example 3: Using a CDN for Static Assets

Your WordPress site serves images, CSS, or JavaScript files from a CDN, but they are blocked.

Error Message:

Access to script at ‘https://cdn.example.com/script.js’ from origin ‘https://yourwordpresssite.com’ has been blocked by CORS policy: The ‘Access-Control-Allow-Origin’ header contains multiple values ‘*, *’, but only one is allowed.

Method to Fix: If you’re using Apache, you can add the following to your configuration file:

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

If you’re using Nginx, add this to your configuration:

location / {
    add_header 'Access-Control-Allow-Origin' '*';
}

Example 4: Making AJAX Requests

Your WordPress site makes AJAX requests to a custom REST API endpoint on a different subdomain, but they are blocked.

Error Message:

Access to XMLHttpRequest at ‘https://api.yourwordpresssite.com/endpoint’ from origin ‘https://yourwordpresssite.com’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

Method to Fix: Install & activate the Enable CORS plugin, then configure the settings to allow your subdomain.

Example 5: Embedding Third-Party Widgets

Your WordPress site embeds widgets from other domains using iframes, but they do not load.

Error Message:

Access to resource at ‘https://widget.example.com/’ from origin ‘https://yourwordpresssite.com’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

Method to Fix: Request the third-party provider to add your domain to their Access-Control-Allow-Origin header. Alternatively, you can try adding the following to your .htaccess file:

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

Know about: What are 404 Errors? How Do I Fix Them

Other Methods to Resolve CORS Errors in WordPress

Here are some additional methods to resolve CORS errors and ensure seamless functionality of your WordPress site.

  • Using Cloudflare: If you are using Cloudflare, you can configure custom rules to manage CORS headers through the Cloudflare dashboard. Cloudflare Workers can also be used to add or modify headers as requests pass through their network.
  • Modifying the Theme’s functions.php File: Another way is by adding code to your Theme’s functions.php file. Insert the following code to enable CORS:
function add_cors_headers() {
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
    header("Access-Control-Allow-Headers: Content-Type, Authorization");
}
add_action('init', 'add_cors_headers');
  • Using CORS Proxy: A CORS proxy acts as an intermediary server that handles requests between your site and the external resource. It adds the necessary CORS headers before forwarding the response to your site.
  • Custom Middleware: Implement custom middleware on your server to add the necessary CORS headers to responses. This can be done using server-side scripting languages like PHP, Node.js, or Python.
  • Third-Party Services: Some third-party services and APIs offer built-in support for CORS. Check the documentation of the external service to see if they provide options for enabling CORS for your domain.
  • Contacting the External Server Provider: Reach out to the provider of the external resource and request them to add your domain to their Access-Control-Allow-Origin header.
  • Configuring Server Settings: You can configure your server settings to fix CORS errors. For example, if you are using Apache, you can add the following to your configuration file:
<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
    Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
    Header set Access-Control-Allow-Headers "Content-Type, Authorization"
</IfModule>

For Nginx, you can use:

location / {
    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';
        return 204;
    }
    add_header 'Access-Control-Allow-Origin' '*';
}

Also read: How to Fix 301 Errors in WordPress

Struggling with Technical Problems on Your WordPress Site?

Don’t let technical challenges disrupt your website’s performance. Get expert help right away! We’re here to ensure your site runs flawlessly.

How to Test If the CORS Issue Is Resolved?

First, refresh your WordPress site to see if the changes take effect. Sometimes, a simple reload can show if the CORS error is fixed.

  • Check the Browser Console: Open your browser’s developer tools, go to the “Console” tab, and look for any CORS-related error messages. If there are none, the issue might be resolved.
  • Review Network Requests: Switch to the “Network” tab in the developer tools and reload the page. Here, check if the previously failing requests have been rectified. Also, click on these requests to see if the correct headers are in place.
  • Test Functionality: Check to see if the features that were failing due to CORS errors, like API calls, font loading, or AJAX requests, are now working as expected.

You can also use online CORS checking tools to verify if the external resources you are accessing are correctly configured to allow cross-origin requests.

Learn: How to Run a Usability Test on WordPress Sites

Best Practices for CORS Configuration

By following these best practices, you can configure CORS securely and ensure your WordPress site remains protected while functioning smoothly.

  • Allow Specific Origins: Instead of allowing all origins with a wildcard (*), specify the exact origins permitted to access your resources. This enhances security by limiting access to trusted domains.
  • Limit Allowed Methods: Only allow the HTTP methods that are necessary for your application, such as GET, POST, and OPTIONS. This minimizes the risk of unauthorized actions.
  • Restrict Headers: Only allow specific headers that your application needs. This prevents unnecessary exposure of sensitive information. For example, allow “Content-Type” and “Authorization” if they are required.
  • Use Preflight Requests: For requests that might have side effects on server data, ensure that preflight requests are used. This involves the browser sending an OPTIONS request to check permissions before making the actual request.
  • Set Appropriate Max Age: Define the Access-Control-Max-Age header to specify how long the results of a preflight request can be cached. This reduces the number of preflight requests your server handles, improving performance.

Lastly, regularly review and monitor your CORS configuration to ensure it meets your security and functionality requirements. Update settings as your application evolves.

Further learning: WordPress Database Performance Optimization

Wrap Up

Addressing CORS errors in WordPress is essential to maintain the functionality and user experience of your website. By understanding common scenarios and applying the appropriate fixes, you can effectively resolve these issues. 

However, if you continue to encounter problems or if the solutions seem too complex, don’t hesitate to seek professional help. Professional WordPress support services, like the one provided by Seahawk, can offer expert assistance, ensuring your site runs smoothly without any CORS-related disruptions.

Related Posts

Malware injected into WordPress sites threatens severe disruptions like breaking site functionality, stealing admin credentials

When it comes to starting a successful online store, having a well-designed WordPress theme is

A website’s logo is a crucial part of website design and brand identity. A well-designed

Regina Patil November 11, 2024

Kentico to WordPress: A Step-by-Step Process for Migrating Your Website

Kentico and WordPress are both popular content management systems (CMS), but they cater to different

WordPress
Regina Patil November 7, 2024

35+ Ways to Speed Up WordPress Site and Slow Admin Dashboard

Is your WordPress admin dashboard slow? Here are actionable ways to speed up WP-admin in

WordPress
Regina Patil November 6, 2024

How to Integrate Salesforce into WordPress: All You Need to Know

Did you know that integrating Salesforce with a WordPress site can streamline lead management and

WordPress

Get started with Seahawk

Sign up in our app to view our pricing and get discounts.