如何以编程方式上传到wordpress - 保存文件问题

kli*_*irr 3 wordpress image-upload

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

目标是遍历数据并在循环中创建Worpress帖子,其中包含post_meta product_image的图片,如: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);
    } 
Run Code Online (Sandbox Code Playgroud)

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

它似乎正确地存储在数据库中,但是由wordpress创建的图像,例如:赛车 - 带有螺柱 - 包括 - 免费送货 - 床垫 - 放大器ribb.jpg

图像以六个版本保存,这是正确的,但它们不会保存在上传/ 08中,我希望放置这些图像.

图像存储在这里:

/Applications/MAMP/htdocs/websites/foo.dev/public_html/add/foo/uploads/
Run Code Online (Sandbox Code Playgroud)

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

小智 11

使用此代码 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;
            }

          ?>
Run Code Online (Sandbox Code Playgroud)


小智 7

虽然我没有针对您的具体问题进行修复,但我看到您要完成的工作,我建议使用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);
Run Code Online (Sandbox Code Playgroud)

你可以使用:

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

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

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


P_E*_*que 6

wp_insert_attachment不会将文件移动到任何地方.您必须将它们自己移动到正确的文件夹中.从WordPress函数参考:"使用绝对路径而不是文件的URI.文件必须在uploads目录中."

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

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

在你的$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 );
Run Code Online (Sandbox Code Playgroud)