WP REST API Upload Image Media

By | May 22, 2017

WordPress WP REST API V2 tutorial and code example upload image / media with PHP cURL.

In the media section ow WP REST API V2 there is a function that we also can upload media / image / attachment into a wordpress website. This function need authentication when call the api. Bellow is a code example of creating (upload ) image / media with WP REST API in php curl language.

$file = 'http://somewebsite/picture.jpg';
$data = file_get_contents($file);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://yourwebsite/wp/wp-json/wp/v2/media");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data );
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, "username" . ":" . "password");
$headers = array(
    "cache-control: no-cache",
    "content-disposition: attachment; filename=rest-api-media.jpg",
    "content" => $data,
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
    if (curl_errno($ch)) {
}
curl_close ($ch);

//check response
echo '<pre>'.print_r(json_decode($result, true), true).'</pre>';

If this process succed you can get media details response.

Related Posts

WP REST API V2 Auth

WP REST API Create Post with jQuery Ajax

Wordpress WP REST API v2 tutorial create post with jquery ajax using basic authentication with code example

WP REST API V2 Auth

WP REST API Edit Post PHP cURL

Wordpess Tutorial WP REST API V2 Update Post by post id with PHP cURL

WP REST API V2 Auth

WP REST API Create Comment Into A Post

Wordpress Tuorial WP REST API Create Comment Into A Post.

wp rest api v2

WP Rest API V2 Introduction

WP Rest API V2 Introduction. WordPress is one of the most used content management system (CMS) in the world.

WP REST API V2 Auth

WP REST API Create Post With PHP cURL

Create post in WP REST API V2 with PHP cURL. Wordpress tutorial creating post with WP REST API / WP-JSON using PHP cURL script.