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
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.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.I had the same problem a few months ago.
Fixed it by adding the following code to the functions.php