Skip to content

Instantly share code, notes, and snippets.

@thoronas
Last active August 29, 2015 14:24
Show Gist options
  • Save thoronas/2876f159404b7547d89b to your computer and use it in GitHub Desktop.
Save thoronas/2876f159404b7547d89b to your computer and use it in GitHub Desktop.
Function for uploading images from URL to WordPress. Thanks to Andrew Norcross for help with this.
<?php
function upload_external_image( $post_id, $img_url ) {
// load media handlers
require_once( ABSPATH . 'wp-admin' . '/includes/image.php' );
require_once( ABSPATH . 'wp-admin' . '/includes/file.php' );
require_once( ABSPATH . 'wp-admin' . '/includes/media.php' );
// create a temp file
$temp_file = download_url( $img_url );
// make a file array
$file_array = array(
'name' => basename( $img_url ),
'tmp_name' => $temp_file,
);
// Check for download errors
if ( is_wp_error( $temp_file ) ) {
@unlink( $file_array[ 'tmp_name' ] );
return $temp_file;
}
// run sideload function
$image_id = media_handle_sideload( $file_array, $post_id );
// Check for handle sideload errors.
if ( is_wp_error( $image_id ) ) {
@unlink( $file_array['tmp_name'] );
return $image_id;
}
// send back the image ID
return $image_id;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment