1. Understand CORS Basics
CORS is a security feature implemented by browsers that restricts web pages from making requests to a different origin than the one that served the original web page. This is crucial for security but can cause issues when you’re trying to make API requests from a different domain (e.g., from your React application to your WordPress backend).
2. WordPress Function to Add CORS Headers
In your WordPress theme’s functions.php file or in a custom plugin file, add the following PHP function to add CORS headers to your HTTP responses:
// Add CORS headers
function add_cors_headers() {
// Replace '*' with your React application URL during production
if (!headers_sent() && $_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Authorization");
header("Access-Control-Max-Age: 86400"); // 1 day
header("Content-Length: 0");
header("Content-Type: text/plain");
exit(0);
}
}
add_action('init', 'add_cors_headers');
3. Explanation of the Code
add_cors_headersfunction: This function adds CORS headers to every HTTP response that WordPress sends.Access-Control-Allow-Origin:Sets the origin that’s allowed to access the resources. In this example,*allows any origin. Replace*with your actual React application URL during production for better security.Access-Control-Allow-Methods:Specifies the HTTP methods allowed when accessing the resources. Adjust as per your API’s requirements.Access-Control-Allow-Headers:Specifies the headers allowed when accessing the resources.Access-Control-Max-Age:Specifies how long (in seconds) the results of a preflight request (OPTIONS request) can be cached.
4. Testing and Adjustments
- Testing: After adding the function, test your React application to ensure that it can now make requests to your WordPress backend without CORS issues.
- Security Considerations: In production, replace
*with the actual domain of your React application to restrict access to only trusted origins.
5. Additional Considerations
- Plugin vs. Theme Function: Depending on your setup, you might prefer placing this function in a custom plugin rather than directly in your theme’s
functions.phpfile for better organizational practices and easier maintenance. - Security: Always validate and sanitize incoming data on your server-side to prevent security vulnerabilities.
By following these steps, you can effectively enable CORS support in your WordPress site, allowing your React frontend or any other frontend application to communicate with your WordPress backend API seamlessly. Adjust the headers as per your specific application’s needs and security requirements.