get image from external url and save to wordpress media library

//get image from external url and save to wordpress media library and set as featured image

$url = "http://yoursite.com/wp-content/uploads/2011/02/14/image_name.jpg";
$post_id = 1;
$att_id = aladdin_get_image_id($url);
if($att_id){
set_post_thumbnail( $post_id, $att_id );
}else{
// Need to require these files
if ( !function_exists('media_handle_upload') ) {
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}

$tmp = download_url( $url );
if( is_wp_error( $tmp ) ){
// download failed, handle error
}

$desc = get_the_title($post_id);
$file_array = array();

// Set variables for storage
// fix file filename for query strings
preg_match('/[^?]+.(jpg|jpe|jpeg|gif|png)/i', $url, $matches);
$file_array['name'] = basename($matches[0]);
$file_array['tmp_name'] = $tmp;

// If error storing temporarily, unlink
if ( is_wp_error( $tmp ) ) {
@unlink($file_array['tmp_name']);
$file_array['tmp_name'] = '';
}

// do the validation and storage stuff
$id = media_handle_sideload( $file_array, $post_id, $desc );

// If error storing permanently, unlink
if ( is_wp_error($id) ) {
@unlink($file_array['tmp_name']);
return $id;
}

set_post_thumbnail( $post_id, $id );

// retrieves the attachment ID from the file URL
function aladdin_get_image_id($image_url) {
global $wpdb;
$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url ));
return $attachment[0];
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *