skip to Main Content

I’m building a headless wordpress site with Nextjs. I’m trying to make an api call to my wordpress CMS.

When fetching data from wordpress I can’t get pass the cors. Couldn’t really find a way to add Access-Control-Allow-Origin to my api call. Ive been trying to do it like this, but still got the CORS error.

$headers = array('Access-Control-Allow-Origin: *; Content-Type: application/json; Accept: application/json');

wp_mail('[email protected]', 'subject', 'msg', $headers);

2

Answers


  1. None of the headers you are dealing with are SMTP headers. They should not go anywhere near the wp_mail function.

    CORS response headers (Access-Control-Allow-*) are HTTP response headers.

    Generally with PHP, you need to add them to the HTTP response with the header() function.

    header("Access-Control-Allow-Origin: *");
    

    Since you are using WordPress (which I’m not hugely familiar with), look at this answer as it seems to wrap itself around the normal headers API.

    Content-Type: application/json might an HTTP request or response header. It isn’t clear from the context as your code snippet doesn’t include anything to read the request body or generate the response body.

    Accept: application/json is an HTTP request header and needs to be sent from the browser to the server. You shouldn’t set it in PHP at all.

    Login or Signup to reply.
  2. I had the same problem a few months ago.

    Fixed it by adding the following code to the functions.php

      // Allow from any origin
      if (isset($_SERVER['HTTP_ORIGIN'])) {
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
      }
    
      // Access-Control headers are received during OPTIONS requests
      if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
          // may also be using PUT, PATCH, HEAD etc
          header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         
    
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
          header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
    
        exit(0);
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search