dongshou9878 2018-10-13 04:08
浏览 115

从URL下载图像并上传到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;
      }
  }
}
  • 写回答

1条回答 默认 最新

  • dosf40815 2019-04-30 05:02
    关注

    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;
    
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条