Skip to content

Instantly share code, notes, and snippets.

@8ig8
Created April 17, 2012 03:50
Show Gist options
  • Save 8ig8/2403342 to your computer and use it in GitHub Desktop.
Save 8ig8/2403342 to your computer and use it in GitHub Desktop.
How To Locally Mirror Remote Images With WordPress
<?php
/*
How To Locally Mirror Remote Images With WordPress
Source: http://forrst.com/posts/Locally_Mirror_Remote_Images_With_WordPress-XSE
*/
// URL of the image you want to mirror. Girl in pink underwear for instance.
$image = 'http://i.imgur.com/Hq4QA.jpg';
// GET request
$get = wp_remote_get( $image );
// Check content-type (eg image/png), might want to test & exit if applicable
$type = wp_remote_retrieve_header( $get, 'content-type' );
// Mirror this image in your upload dir
$mirror = wp_upload_bits( basename( $image ), '', wp_remote_retrieve_body( $get ) );
/* Sample output for mirror:
array(3) {
["file"]=>
string(64) "E:\home\planetozh\wordpress/wp-content/uploads/2010/09/Hq4QA.jpg"
["url"]=>
string(63) "http://127.0.0.1/wordpress/wp-content/uploads/2010/09/Hq4QA.jpg"
["error"]=>
bool(false)
}
*/
// Attachment options
$attachment = array(
'post_title'=> basename( $image ),
'post_mime_type' => $type
);
// Add the image to your media library (won't be attached to a post)
wp_insert_attachment( $attachment, $mirror['file'] );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment