How to retrieve image from URL and set as featured image post thumbnail. My favorite way of handling this problem has been to use a little documented function I discovered on another stack post: media_sideload_image
It works by fetching an image url to the WordPress upload dir and then associating the image to a post’s attachments.
You can try it like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | // required libraries for media_sideload_image require_once(ABSPATH . 'wp-admin/includes/file.php'); require_once(ABSPATH . 'wp-admin/includes/media.php'); require_once(ABSPATH . 'wp-admin/includes/image.php'); // $post_id == the post you want the image to be attached to // $video_thumb_url == the vimeo video's thumb url // $description == optional description // load the image $result = media_sideload_image($video_thumb_url, $post_id, $description); // then find the last image added to the post attachments $attachments = get_posts(array('numberposts' => '1', 'post_parent' => $post_id, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC')); if(sizeof($attachments) > 0){ // set image as the post thumbnail set_post_thumbnail($post_id, $attachments[0]->ID); } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.