How to Upload an Image Using the WordPress REST API – 2023

Hello, WordPress coders! Today we’re going to learn how to upload an image to your WordPress site using the REST API. WordPress REST API is a great way to interact with your site remotely, and one of its uses is programmatically uploading images to your media library. So, buckle up and let’s get started!

Step 1: Generate a Basic Authentication Header

To upload an image via the REST API, we first need to authenticate ourselves. We’ll be using Basic Authentication. Here’s how to generate an authentication header:

  1. Concatenate your WordPress username and password with a colon. For example, if your username is “admin” and password is “password”, you’ll get “admin:password”.
  2. Encode this string in Base64. There are many online tools you can use for this, or you can use the btoa() function in JavaScript in your browser’s console.
  3. Prepend the string with “Basic “. The final result will look something like this: “Basic YWRtaW46cGFzc3dvcmQ=”.

Keep this authentication string safe – you’ll need it in the next step.

Step 2: Use cURL to Upload an Image

Next, we’re going to use cURL, a command-line tool for making HTTP requests, to upload our image. Here’s a simple example:

				
					curl --request POST --url http://example.com/wp-json/wp/v2/media \
--header "Authorization: Basic YWRtaW46cGFzc3dvcmQ=" \
--header "Content-Disposition: attachment; filename=example.jpg" \
--header "Content-Type: image/jpeg" \
--data-binary "@/path/to/your/image.jpg"

				
			

This cURL command does the following:

  1. Makes a POST request to the /wp/v2/media endpoint of the WordPress REST API. Make sure to replace “http://example.com” with your own site’s URL.
  2. Includes the Basic Authentication header we generated in step 1.
  3. Includes a Content-Disposition header which specifies the filename for the uploaded image.
  4. Includes a Content-Type header to tell WordPress that we’re uploading an image.
  5. Uploads the binary data of the image itself. Replace “/path/to/your/image.jpg” with the actual path to your image.

That’s it! If everything goes well, this command will upload your image to the WordPress media library, and the REST API will return a JSON response with the details of the uploaded image.

Please note that cURL is a command-line tool, so you’ll need to run this command in your system’s terminal (Linux/macOS) or Command Prompt (Windows), not in your PHP or JavaScript code.

By following these steps, you’ve learned how to upload an image to your WordPress site using the REST API. This is a powerful tool for interacting with your site remotely, and this is just one of its many uses. Keep exploring and happy coding!

Table of Contents

Pro Feature

When to Use This Feature

Use Examples