Wordpress:使用php上传图片 - 无法创建不同的图片尺寸

时间:2015-06-14 16:32:34

标签: php wordpress image file-upload

我正在尝试模拟wordpress默认上传过程。 这里是图片:

  <input type="file" name="imgsupload1[]" id="imgsupload1[]" multiple="">

应上传的代码:

$post_imgs = $_FILES['imgsupload1'];    
foreach ($post_imgs['name'] as $key => $value) {
      if ($post_imgs['name'][$key]) {
        $file = array(
          'name'     => $post_imgs['name'][$key],
          'type'     => $post_imgs['type'][$key],
          'tmp_name' => $post_imgs['tmp_name'][$key],
          'error'    => $post_imgs['error'][$key],
          'size'     => $post_imgs['size'][$key]
        );
        $img_caption = $img_captions[urlencode(basename($file['name']))];
        $new_file = wp_handle_upload($file, array( 'test_form' => false ));

    $filename = $new_file['url'];
    $filetype = wp_check_filetype( basename( $filename ), null );
    $wp_upload_dir = wp_upload_dir();

    // Prepare an array of post data for the attachment.
    $attachment = array(
        'guid'           => $wp_upload_dir['url'].'/'.basename( $filename ), 
        'post_mime_type' => $filetype['type'],
        'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
        'post_content'   => '',
        'post_status'    => 'inherit',
        'post_excerpt' => $img_caption
    );

    require_once( ABSPATH.'wp-admin/includes/image.php' );
    $img_id = wp_insert_attachment( $attachment, $filename, $post_id );
    $img_data = wp_generate_attachment_metadata( $img_id, $wp_upload_dir['basedir'].'/'.basename( $filename ) );
    wp_update_attachment_metadata( $img_id, $img_data );

      }   // IF IMAGE[KEY] EXISTS
    }   // FOREACH UPLOADED IMAGE

不会创建默认定义的图像大小。 似乎问题出在wp_generate_attachment_metadata

1 个答案:

答案 0 :(得分:0)

问题在于wp_generate_attachment_metadata,为了传递正确的绝对路径,你需要在wp_upload_dir数组中使用'path'元素:

$img_data = wp_generate_attachment_metadata( $img_id, $wp_upload_dir['path'].'/'.basename( $filename ) );

这与Codex中的内容不同。 希望它会帮助别人。