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 Edit Post PHP cURL

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

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 Get Post By Id With PHP

WordPress WP REST API V2 Tutorial get post by post id using php script.

Change Search Permalink WordPress

How to change search slug permalink wordpress with any words you want

WP REST API V2 Auth

Autocomplete WordPress Search Form With WP REST API

WordPress Tutorial Create Autocomplete Search Form Using WP REST API V2 With Code Example