从URL下载图像并上传到WordPress媒体库

时间:2018-10-13 04:08:43

标签: php wordpress

我正在尝试构建一个WordPress函数,该函数需要一个图像URL,下载图像,将其上传到媒体库,然后返回图像ID。

我从this answertaken from here改编而成,最后添加了wp_insert_attachment()

此刻它不起作用,因为它不返回任何内容或上传任何媒体。

我厌倦了通过逐步使用var_dump()进行调试的过程,发现$url参数已正确传递,但是download_url却没有任何输出。

你知道怎么了吗?

您能在功能中看到其他可能损坏的东西吗?

/* 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;
      }
  }
}

2 个答案:

答案 0 :(得分:1)

更新的代码: 在您网站的根目录上创建任何文件。并添加以下代码。使用任何图像网址更改IMAGEURL。

<?php 
include( 'wp-load.php' );
include_once( ABSPATH . '/wp-admin/includes/image.php' );

$imageurl = 'IMAGEURL';
$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;
 ?>

答案 1 :(得分:0)

100%使用此代码

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;