Last active
January 16, 2018 23:36
-
-
Save sergeliatko/f27003d2d75c03dfa2f966f9a08a8890 to your computer and use it in GitHub Desktop.
PHP function to import an image from URL into WordPress media library
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 | |
/** | |
* Imports an image from URL into media libarary. | |
* | |
* @param string $url The image URL | |
* @param string|null $title The title to use for image in the media library (also will be added as ALT text) | |
* @param int $post_parent_id Post parent ID if applicable | |
* | |
* @return int|\WP_Error ID of the newly created attachment or Wp_Error object on failure | |
*/ | |
function import_image_from_url( $url, $title = null, $post_parent_id = 0 ) { | |
// sanitize url before processing | |
$url = esc_url_raw( $url, array( 'http', 'https' ) ); | |
if ( empty( $url ) ) { | |
return new WP_Error( 400, 'Empty or invalid URL' ); | |
} | |
// fix file name before we start | |
preg_match( '/[^\/]+\.(jpe?g|jpe|gif|png)\b/i', $url, $matches ); | |
/** @var string $name */ | |
$name = sanitize_file_name( $matches[0] ); | |
if ( empty( $name ) ) { | |
return new WP_Error( 400, 'Invalid file name' ); | |
} | |
// make sure all necessary functions are loaded | |
if ( ! function_exists( 'download_url' ) ) { | |
require_once( ABSPATH . 'wp-admin/includes/file.php' ); | |
} | |
if ( ! function_exists( 'media_handle_sideload' ) ) { | |
require_once( ABSPATH . 'wp-admin/includes/media.php' ); | |
} | |
if ( ! function_exists( 'wp_read_image_metadata' ) ) { | |
require_once( ABSPATH . 'wp-admin/includes/image.php' ); | |
} | |
// try to download the image to $tmp location | |
/** @var string|\WP_Error $tmp Downloaded temporary file location or WP_Error on failure */ | |
if ( is_wp_error( $tmp = download_url( $url, 30 ) ) ) { | |
return $tmp; | |
} | |
// construct file data | |
$file = array( | |
'name' => $name, | |
'tmp_name' => $tmp | |
); | |
// try to add the description if present | |
$post = empty( $title ) ? array() : array( | |
'meta_input' => array( | |
'_wp_attachment_image_alt' => $title | |
) | |
); | |
// try to upload the image to media library | |
/** @var int|\WP_Error $id */ | |
$id = media_handle_sideload( $file, $post_parent_id, $title, $post ); | |
// delete the temporary file | |
@unlink( $tmp ); | |
// return the attachment ID or WP_Error on failure | |
return $id; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment