Tuesday, March 31, 2015

Programmatically setting Featured Image for Post using an image on a remote server

In one of my applications we have built a small module that allows other applications to programmatically add posts in our CMS site that is powered by Wordpress. One of the things I got a bit stuck in was setting the featured image of the post. The image resided in a S3 bucket so I basically had to download it to the WordPress server, upload it to the media directory and then set the featured image option of the post to this newly uploaded image.

The media_sideload_image function is what i ended up using after a lot of googling for options.



/**
$url : The full url of the image starting with the protocol.
$post_id : The post you want to add the featured image to.
*/
function add_image_to_post($url, $post_id){
 $desc = "Auto added";
 $image_url = '';
 // The method returns either a string or error

 $image = media_sideload_image($url, $post_id, $desc);
 if(!is_string($image)){
   // Something went wrong
  return;
 }
 // Getting the url of the image. The method returns html
 // code with the img tag.
 $doc = new DOMDocument();
 $doc->loadHTML($image);
 $imageTags = $doc->getElementsByTagName('img');
 foreach($imageTags as $tag) {
  $image_url = $tag->getAttribute('src');
 }
 // get the attachment id from the url so that we can add that to the post.
 $attach_id = fjarrett_get_attachment_id_by_url($image_url);
 // Adding the image as featured image
 update_post_meta($post_id, '_thumbnail_id', $attach_id);
}

The fjarrett_get_attachment_id_by_url is something I picked up from Frankie Jarrett's blog. It works really well.

No comments:

Post a Comment