Seems pretty simple. Only catch is if you aren’t on admin area, you must include some libraries from within WordPress includes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | // only need these if performing outside of admin environment require_once(ABSPATH . 'wp-admin/includes/media.php'); require_once(ABSPATH . 'wp-admin/includes/file.php'); require_once(ABSPATH . 'wp-admin/includes/image.php'); // example image $image = 'http://example.com/logo.png'; // magic sideload image returns an HTML image, not an ID $media = media_sideload_image($image, $post_id); // therefore we must find it so we can set it as featured ID if(!empty($media) && !is_wp_error($media)){ $args = array( 'post_type' => 'attachment', 'posts_per_page' => -1, 'post_status' => 'any', 'post_parent' => $post_id ); // reference new image to set as featured $attachments = get_posts($args); if(isset($attachments) && is_array($attachments)){ foreach($attachments as $attachment){ // grab source of full size images (so no 300x150 nonsense in path) $image = wp_get_attachment_image_src($attachment->ID, 'full'); // determine if in the $media image we created, the string of the URL exists if(strpos($media, $image[0]) !== false){ // if so, we found our image. set it as thumbnail set_post_thumbnail($post_id, $attachment->ID); // only want one image break; } } } } |
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.