Skip to content

Instantly share code, notes, and snippets.

@jbrinley
Last active August 10, 2018 12:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jbrinley/e94a235d37413483aa94d2e91df55ce8 to your computer and use it in GitHub Desktop.
Save jbrinley/e94a235d37413483aa94d2e91df55ce8 to your computer and use it in GitHub Desktop.
A utility class for importing images from an external URL into WordPress.
<?php
/**
* Class Image_Importer
*
* Imports an image from a URL and attaches it to a post
*/
class Image_Importer {
private $image_url;
private $attach_to_post_id;
public function __construct( $image_url, $attach_to_post_id = 0 ) {
$this->image_url = $image_url;
$this->attach_to_post_id = $attach_to_post_id;
}
public function import() {
$this->require_files();
$tmp = download_url( $this->image_url );
if ( is_wp_error( $tmp ) ) {
return false;
}
$path = parse_url( $this->image_url, PHP_URL_PATH );
$file_array = [
'name' => basename( $path ),
'tmp_name' => $tmp,
];
$image_id = media_handle_sideload( $file_array, $this->attach_to_post_id );
if ( is_wp_error( $image_id ) ) {
unlink( $tmp );
return false;
}
return $image_id;
}
private function require_files() {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
}
}
@jbrinley
Copy link
Author

jbrinley commented Jul 9, 2018

Usage:

$importer      = new Image_Importer( $remote_url, $parent_post_id );
$attachment_id = $importer->import();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment