【问题标题】:How to upload to wordpress programmatically - saving files issue如何以编程方式上传到 wordpress - 保存文件问题
【发布时间】:2013-08-19 00:41:10
【问题描述】:

我有循环遍历的数据,这些数据包括标题、内容、服务器上文件的路径以及各种其他信息。

目标是遍历数据并在循环中创建带有 post_meta product_image 的图片的 Worpress 帖子 比如:add_post_meta ($ post_id, '_product_image', $ attach_id, true);

我的循环如下所示:

    while($row = $STH->fetch()) {  

        $my_post = array(
          'post_title'    => $row->title,
          'post_content'  => $row->description,
          'post_status'   => 'publish',
          'post_author'   => $current_user->ID,
          'post_category' => array(6)
        );


        // Insert the post into the database
        $post_id = wp_insert_post( $my_post );

        add_post_meta( $post_id, 'product_price', 199, true );
        add_post_meta( $post_id, 'product_sub_price', 20, true);

        require_once(ABSPATH . 'wp-admin/includes/image.php');
        require_once(ABSPATH . 'wp-admin/includes/media.php');
        require_once(ABSPATH . 'wp-admin/includes/file.php');

        $filename = $row->image_local_name;

        // Path to the file i want to upload into wordpress.
        $path = ABSPATH . 'add/foo/uploads/' . $row->image_local_name;  // Path to file.
        var_dump($path);

        $file_url = $row->image_url;
        $filename = $row->image_local_name;

        $wp_filetype = wp_check_filetype(basename($filename), null );

        $wp_upload_dir = wp_upload_dir();

        // Path i want to save the image(s).
        $save_path = $wp_upload_dir['basedir'] . $wp_upload_dir['subdir'] . $filename;
        var_dump($save_path);


        $attachment = array(
            'post_author' => $current_user->ID, 
            'post_date' => current_time('mysql'),
            'post_date_gmt' => current_time('mysql'),
            'post_title' => $filename, 
            'post_status' => 'inherit',
            'comment_status' => 'closed',
            'ping_status' => 'closed',
            'post_name' => $filename,                                           
            'post_modified' => current_time('mysql'),
            'post_modified_gmt' => current_time('mysql'),
            'post_parent' => $post_id,
            'post_type' => 'attachment',
            'guid' =>  $wp_upload_dir['basedir'] . $filename,   // not sure if this is correct, some advise?
            'post_mime_type' => $wp_filetype['type'],
            'post_excerpt' => '',
            'post_content' => ''
        );


        $attach_id = wp_insert_attachment( $attachment, $save_path, $post_id );

        var_dump($attach_id);

        $attach_data = wp_generate_attachment_metadata( $attach_id, $path );

        var_dump($attach_data);

        $update = wp_update_attachment_metadata( $attach_id,  $attach_data );

        var_dump($update);

        // Add the attach_id to post_meta key: product_image with the value of the attach_id
        add_post_meta( $post_id, '_product_image', $attach_id, true);
    } 

输出:http://pastebin.com/LpNzc1pP

似乎在数据库中存储正确,但是wordpress创建的图像,例如:racing cars-with-studs-including-free-shipping-mattress-amp ribb.jpg

图像保存在六个版本中,这是正确的,但它们没有保存在我希望放置这些图像的 uploads/08 中。

图像存储在这里:

/Applications/MAMP/htdocs/websites/foo.dev/public_html/add/foo/uploads/

如何将这些图像保存在正确的位置?

【问题讨论】:

    标签: wordpress image-upload


    【解决方案1】:

    wp_insert_attachment 不会将文件移动到任何地方。您必须自己将它们移动到正确的文件夹中。来自WordPress Function Reference:“使用绝对路径而不是文件的 URI。文件必须位于上传目录中。”

    我建议使用wp_upload_bits 函数来移动文件,因为该函数知道您的博客是否设置为每年/每月目录,并为您提供文件的路径和 URL:

    $upload = wp_upload_bits( $filename, null, file_get_contents($path) );
    if ( $upload['error'] )
        echo "Failed uploading: " . $upload['error'];
    

    在您的$attachment 数组中,使用['guid'] => $upload['url'],然后:

    $attach_id = wp_insert_attachment( $attachment, $upload['file'], $post_id );
    $attach_data = wp_generate_attachment_metadata( $attach_id, $upload['file'] );
    $update = wp_update_attachment_metadata( $attach_id, $attach_data );
    

    【讨论】:

      【解决方案2】:

      虽然我没有针对您的具体问题的解决方案,但我知道您正在尝试完成什么,并且我建议使用 Wordpress API media_handle_sideload() 或 media_sideload_image() 函数将图像文件放入的替代方法媒体库并将它们自动附加到帖子中。

      所以不是:

          $filename = $row->image_local_name;
      
          $wp_filetype = wp_check_filetype(basename($filename), null );
      
          $wp_upload_dir = wp_upload_dir();
      
          // Path i want to save the image(s).
          $save_path = $wp_upload_dir['basedir'] . $wp_upload_dir['subdir'] . $filename;
          var_dump($save_path);
      
      
          $attachment = array(
              'post_author' => $current_user->ID, 
              'post_date' => current_time('mysql'),
              'post_date_gmt' => current_time('mysql'),
              'post_title' => $filename, 
              'post_status' => 'inherit',
              'comment_status' => 'closed',
              'ping_status' => 'closed',
              'post_name' => $filename,                                           
              'post_modified' => current_time('mysql'),
              'post_modified_gmt' => current_time('mysql'),
              'post_parent' => $post_id,
              'post_type' => 'attachment',
              'guid' =>  $wp_upload_dir['basedir'] . $filename,   // not sure if this is correct, some advise?
              'post_mime_type' => $wp_filetype['type'],
              'post_excerpt' => '',
              'post_content' => ''
          );
      
      
          $attach_id = wp_insert_attachment( $attachment, $save_path, $post_id );
      
          var_dump($attach_id);
      
          $attach_data = wp_generate_attachment_metadata( $attach_id, $path );
      
          var_dump($attach_data);
      
          $update = wp_update_attachment_metadata( $attach_id,  $attach_data );
      
          var_dump($update);
      
          // Add the attach_id to post_meta key: product_image with the value of the attach_id
          add_post_meta( $post_id, '_product_image', $attach_id, true);
      

      你可以使用:

      $myAttachmentId = media_handle_sideload( $file_url, $post_id );

      这会将图片作为帖子的附件上传到媒体库,然后您可以通过以下方式将其设为“产品图片”:

      $myProductImage = add_post_meta( $post_id, '_product_image', $myAttachmentId, true );

      【讨论】:

        【解决方案3】:

        使用此代码 100% 有效

        <form method="post" enctype="multipart/form-data">
              <input type="file" name="fileToUpload">
              <input type="submit" name="upload" value="Upload">
        </form>
        <?php
            if(@$_POST['upload']){
                        $file_name = $_FILES['fileToUpload']['name'];
                        $file_temp = $_FILES['fileToUpload']['tmp_name'];
        
                        $upload_dir = wp_upload_dir();
                        $image_data = file_get_contents( $file_temp );
                        $filename = basename( $file_name );
                        $filetype = wp_check_filetype($file_name);
                        $filename = time().'.'.$filetype['ext'];
        
                        if ( wp_mkdir_p( $upload_dir['path'] ) ) {
                          $file = $upload_dir['path'] . '/' . $filename;
                        }
                        else {
                          $file = $upload_dir['basedir'] . '/' . $filename;
                        }
        
                        file_put_contents( $file, $image_data );
                        $wp_filetype = wp_check_filetype( $filename, null );
                        $attachment = array(
                          'post_mime_type' => $wp_filetype['type'],
                          'post_title' => sanitize_file_name( $filename ),
                          'post_content' => '',
                          'post_status' => 'inherit'
                        );
        
                        $attach_id = wp_insert_attachment( $attachment, $file );
                        require_once( ABSPATH . 'wp-admin/includes/image.php' );
                        $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
                        wp_update_attachment_metadata( $attach_id, $attach_data );
        
                        echo $attach_id;
                    }
        
                  ?>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-03-29
          • 1970-01-01
          • 2012-01-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多