Whenever we’re making remote requests with WordPress, we’re likely going to be using one of the following functions:

And, yes, sometimes we’ll be using cURL depending on the nature of the project, but that’s outside the content of this post.

For this article, I want to talk specifically about making remote requests and specifying headers against a third-party API.

Authorization Headers with WordPress

Whenever it comes making asynchronous requests with WordPress, the process often goes like this:

  1. Set up the JavaScript function to make a call to the server-side (with a secure nonce, of course),
  2. Have the server-side perform the request using one of the aforementioned functions,
  3. Return the response either in the form of a success or error message,
  4. Have the client-side JavaScript handle the response in whatever way seems fitting based on the response.

But what if the API request you need to make from the server requires something more than a basic endpoint with a few parameters?

More specifically, what if what you’re writing requires that you provide some type of authorization for your work? Luckily, WordPress allows us to set headers that solve exactly this.

If you want to implement something like this, then I’m going to assume the content type will be that of JSON and that the authorization will be some type of token (however, your implementation may vary based on the system with which you’re working).

In this case, my token will simply be identified as $token. And here’s a simple example:

View the code on Gist.

Something Worth Noting

If your host is running on Apache and this type of request does not work, then you’re likely going to need to update your htaccess file so that it includes the following rule: SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1.

Props to George for hooking me up with that.


Leave a Reply