Created
July 22, 2016 20:19
-
-
Save lenivene/c0d44c2cc71eeaf1ad9cdb5434376326 to your computer and use it in GitHub Desktop.
Upload image by url
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function wp_upload_image_by_url( $url, $post_ID = 0 ) { | |
require_once( ABSPATH . 'wp-admin/includes/media.php' ); | |
require_once( ABSPATH . 'wp-admin/includes/file.php' ); | |
require_once( ABSPATH . 'wp-admin/includes/image.php' ); | |
if ( '' == $post_id ) | |
return new WP_Error( 'upload_image_by_url_failed', __( 'Invalid post ID' ) ); | |
if( empty( $url ) ){ | |
return new WP_Error( 'upload_image_by_url_failed', __( 'Insert URL' ) ); | |
} | |
else{ | |
/** | |
* Sanitizing URLs | |
*/ | |
$url = esc_url( $url ); | |
/** | |
* Set variables for storage, fix file | |
* filename for query strings. | |
*/ | |
preg_match( '/[^\?]+\.(jpe?g|jpe|gif|png)\b/i', $url, $matches ); | |
if ( ! $matches ) { | |
return new WP_Error( 'upload_image_by_url_failed', __( 'Invalid image URL' ) ); | |
} | |
$file_array = array(); | |
$file_array['name'] = basename( $matches[0] ); | |
/** | |
* Download file to temp location. | |
*/ | |
$file_array['tmp_name'] = download_url( $url ); | |
/** | |
* Check for download errors | |
* if there are error unlink the temp file name | |
*/ | |
if ( is_wp_error( $file_array['tmp_name'] ) ) { | |
return $file_array['tmp_name']; | |
} | |
$image_ID = media_handle_sideload( $file_array, $post_ID ); | |
/** | |
* If error storing permanently, unlink. | |
*/ | |
if ( is_wp_error( $image_ID ) ) { | |
@unlink( $file_array['tmp_name'] ); | |
return $image_ID; | |
} | |
return $image_ID; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment