Skip to content

Instantly share code, notes, and snippets.

@MogulChris
Last active October 31, 2023 03:36
Show Gist options
  • Save MogulChris/336050d460a3c677a79d39002d48f899 to your computer and use it in GitHub Desktop.
Save MogulChris/336050d460a3c677a79d39002d48f899 to your computer and use it in GitHub Desktop.
Programmatically import images into WordPress with PHP
<?php
/**
* Grab a remote image and import it into WordPress with PHP
*/
function mytheme_import_image($image_url){
//$image_url is something like https://www.mysite.com/images/myimage.jpg
//1. Get image
$image_data = file_get_contents($image_url);
//2. Build a filename
$wordpress_upload_dir = wp_upload_dir();
$image_name = basename($image_url); // myimage.jpg
$new_file_path = $wordpress_upload_dir['path'] . '/' . $image_name; // /new/path/to/image.jpg
//if necessary, rename our image until it has a unique filename
$i = 1;
while( file_exists( $new_file_path ) ) {
$i++;
$new_file_path = $wordpress_upload_dir['path'] . '/' . $i . '_' . $image_name;
}
//save image locally
file_put_contents($new_file_path, $image_data);
if(!file_exists($new_file_path)) die("failed to write image locally"); //the image is not where we expect - check file permissions etc
//3. Import into WordPress
$new_file_mime = mime_content_type( $new_file_path );
$upload_id = wp_insert_attachment( array(
'guid' => $new_file_path,
'post_mime_type' => $new_file_mime,
'post_title' => preg_replace( '/\.[^.]+$/', '', $image_name ),
'post_content' => '',
'post_parent' => 0, //you can set this to a post ID if you want to associate this image with existing content
'post_status' => 'inherit'
), $new_file_path );
if(is_wp_error($upload_id)) die($upload_id->get_error_message()); //something went awry
wp_update_attachment_metadata( $upload_id, wp_generate_attachment_metadata( $upload_id, $new_file_path ) );
//Now you can use $image_id however you want, eg update_post_meta($some_post_id, '_thumbnail_id', $upload_id) to set the featured image on $some_post_id
return $upload_id;
}//mytheme_import_image()
?>
@MogulChris
Copy link
Author

Note if you are using this in a bootstrap WP script, you need to require_once('/webs/new/wp-admin/includes/media.php');

@MogulChris
Copy link
Author

NB wp_generate_attachment_metadata seems to be in /wp-admin/includes/image.php (now?)

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