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

WP REST API Get Posts By Category

WordPress REST API tutorial get posts by category id with php script

WP REST API V2 Auth

WP REST API jQuery Ajax Basic Authentication

WP REST API Basic Authentication With Jquery Ajax Tutorial and Code Example

wp rest api v2

WP REST API Get Media Detail By ID

WordPress WP REST API V2 get media attachment by id with php curl tutorial and code example

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.