【问题标题】:Wordpress: uploading images using php - can't create different image sizesWordpress:使用 php 上传图片 - 无法创建不同大小的图片
【发布时间】:2015-08-30 03:52:51
【问题描述】:

我正在尝试模拟 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 中

【问题讨论】:

    标签: php wordpress image file-upload


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2013-10-26
      • 2012-11-07
      • 1970-01-01
      • 2012-08-01
      • 1970-01-01
      • 2023-03-16
      • 2011-08-26
      • 1970-01-01
      • 2014-01-23
      相关资源
      最近更新 更多