Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download image from URL and upload to WordPress media library

Tags:

php

wordpress

I'm trying to build a WordPress function that takes an image URL, downloads the image, uploads it to the media library, and returns the image ID.

I adapted it from this answer which was taken from here, and I added wp_insert_attachment() at the end.

At the moment it doesn't work because it doesn't return anything or upload any media.

I tired debugging by stepping through with var_dump(), and I have discovered the $url parameter is passed in correctly, but nothing is output from download_url.

Do you know what is wrong?

Can you see anything else in the function that might be broken?

/* Add image to media library from URL and return the new image ID */
function bg_image_upload($url) {

  // Gives us access to the download_url() and wp_handle_sideload() functions
  require_once( ABSPATH . 'wp-admin/includes/file.php' );

  // Download file to temp dir
  $timeout_seconds = 10;
  $temp_file = download_url( $url, $timeout_seconds );

  if ( !is_wp_error( $temp_file ) ) {

      // Array based on $_FILE as seen in PHP file uploads
      $file = array(
          'name'     => basename($url), // ex: wp-header-logo.png
          'type'     => 'image/png',
          'tmp_name' => $temp_file,
          'error'    => 0,
          'size'     => filesize($temp_file),
      );

      $overrides = array(
          // Tells WordPress to not look for the POST form
          // fields that would normally be present as
          // we downloaded the file from a remote server, so there
          // will be no form fields
          // Default is true
          'test_form' => false,

          // Setting this to false lets WordPress allow empty files, not recommended
          // Default is true
          'test_size' => true,
      );

      // Move the temporary file into the uploads directory
      $results = wp_handle_sideload( $file, $overrides );

      if ( !empty( $results['error'] ) ) {
          // Insert any error handling here
      } else {

          $filename  = $results['file']; // Full path to the file
          $local_url = $results['url'];  // URL to the file in the uploads dir
          $type = $results['type']; // MIME type of the file
          $wp_upload_dir = wp_upload_dir(); // Get the path to the upload directory.

          $attachment = array (
            'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
            'post_mime_type' => $type,
            'post_status' => 'inherit',
            'post_content' => '',
          );

          $img_id = wp_insert_attachment( $attachment, $filename  );

          return $img_id;
      }
  }
}
like image 811
TinyTiger Avatar asked Jan 28 '23 07:01

TinyTiger


1 Answers

100% working this code

include_once( ABSPATH . 'wp-admin/includes/image.php' );
$imageurl = '<IMAGE URL>';
$imagetype = end(explode('/', getimagesize($imageurl)['mime']));
$uniq_name = date('dmY').''.(int) microtime(true); 
$filename = $uniq_name.'.'.$imagetype;

$uploaddir = wp_upload_dir();
$uploadfile = $uploaddir['path'] . '/' . $filename;
$contents= file_get_contents($imageurl);
$savefile = fopen($uploadfile, 'w');
fwrite($savefile, $contents);
fclose($savefile);

$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
    'post_mime_type' => $wp_filetype['type'],
    'post_title' => $filename,
    'post_content' => '',
    'post_status' => 'inherit'
);

$attach_id = wp_insert_attachment( $attachment, $uploadfile );
$imagenew = get_post( $attach_id );
$fullsizepath = get_attached_file( $imagenew->ID );
$attach_data = wp_generate_attachment_metadata( $attach_id, $fullsizepath );
wp_update_attachment_metadata( $attach_id, $attach_data ); 

echo $attach_id;
like image 142
Mehul Velani Avatar answered Jan 30 '23 03:01

Mehul Velani