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!
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:
btoa()
function in JavaScript in your browser’s console.Keep this authentication string safe – you’ll need it in the next step.
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:
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!
Enables the creation of unique, personalized landing pages at scale by offering unlimited placeholders for dynamic content.
Essential for crafting content-rich, unique pages for each visitor or target group, optimizing for local SEO, e-commerce variability, or specific event details.