Skip to content

Instantly share code, notes, and snippets.

@pablo-sg-pacheco
Created June 28, 2016 14:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pablo-sg-pacheco/5ca988de13daad90868a31e9751606a3 to your computer and use it in GitHub Desktop.
Save pablo-sg-pacheco/5ca988de13daad90868a31e9751606a3 to your computer and use it in GitHub Desktop.
Set thumbnail by external image URL
<?php
function setThumbnailByUrl( $imgUrl, $post_id ) {
$post = get_post($post_id);
$media = media_sideload_image($imgUrl, $post_id, $post->post_title);
// 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;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment