Skip to content

Instantly share code, notes, and snippets.

@ozh
Created September 5, 2010 20:32
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 ozh/566296 to your computer and use it in GitHub Desktop.
Save ozh/566296 to your computer and use it in GitHub Desktop.
<?php
/*
How To Locally Mirror Remote Images With WordPress
*/
// 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