Adding display image to wordpress.com via api

I want to add a new message with my favorite image, but first add the image to the message.

function add_post($access_key,$blogid,$title,$content,$categories_array,$tags_array,$featuredimage) { $options = array ( 'http' => array ( 'ignore_errors' => true, 'method' => 'POST', 'header' => array ( 0 => 'authorization: Bearer '.$access_key, 1 => 'Content-Type: multipart/form-data', ), 'content' => http_build_query( array ( 'title' => $title, 'content' => $content, 'tags' => $tags_array, 'categories' => $categories_array, 'media'=>$featuredimage,///array($featuredimage),//jak nie zadziala to zapakowac w array 'media[]'=>$featuredimage//array($featuredimage) ) ), ), ); $context = stream_context_create( $options ); $response = file_get_contents( "https://public-api.wordpress.com/rest/v1/sites/{$blogid}/posts/new/", false, $context ); $response = json_decode( $response ); return $response; } 

the body of the function was copied from examples and works great, except for adding media

 add_post($_GET['token'],$blog_id,"tytul","tresc",array("cat1"),array("tagt1","tag2"), "http://icons.iconarchive.com/icons/iconka/meow/256/cat-walk-icon.png"); 

add messages without adding an image

in the documentation
http://developer.wordpress.com/docs/api/1/post/sites/ $ site / posts / new / I only found code to add media from the console

 curl \ --form 'title=Image' \ --form 'media[] =@ /path/to/file.jpg' \ -H 'Authorization: BEARER your-token' \ 'https://public-api.wordpress.com/rest/v1/sites/123/posts/new' 

and specify the type of form content

"(...) To load media, the entire request must be multi-part / form data"

but when I changed "application / x-www-form-urlencoded" to "multipart / form-data", ... and nothing changed

+4
source share
1 answer

The media parameter in this API call is only used to load local image files, but you call it with an external URL. Instead, you should use the media_urls parameter. Corresponding bit from the documentation :

media: An array of images to attach to the message. To load media, the entire request must be encoded in multipart / form-data format. Multiple multimedia objects will be displayed in the gallery. Accepts images (image / gif, image / jpeg, image / png).

  Example: curl --form 'title=Image' --form 'media[] =@ /path/to/file.jpg' ... 

media_urls: An array of URLs to attach images to the message. Lock media for publishing.

Your code may change to:

 ... 'content' => http_build_query( array ( 'title' => $title, 'content' => $content, 'tags' => $tags_array, 'categories' => $categories_array, 'media_urls' => array($featuredimage) ) ... 
+2
source

Source: https://habr.com/ru/post/1499362/


All Articles