4

I have data that I loop through, this data includes the title, content, path to the file on the server and various other information.

The goal is to loop through the data and in the loop create Worpress post with a picture that has post_meta product_image like: add_post_meta ($ post_id, '_product_image', $ attach_id, true);

My loop looks like this:

    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);
    } 

Output: http://pastebin.com/LpNzc1pP

It seems that it is stored correctly in the database, but the images created by wordpress, eg: racing cars-with-studs-including-free-shipping-mattress-amp ribb.jpg

The image is saved in six versions, that is correct, but they are not saved in uploads/08 where I want these images to be placed.

Images are stored here:

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

How do I get these images to be saved in the correct place?

4

3 回答 3

7

虽然我没有解决您的具体问题,但我知道您正在尝试完成什么,并且我会建议使用 Wordpress APImedia_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 );

于 2013-12-16T20:21:45.587 回答
7

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

          ?>
于 2019-07-03T05:52:55.620 回答
6

wp_insert_attachment不会将文件移动到任何地方。您必须自己将它们移动到正确的文件夹中。来自WordPress 函数参考:“使用绝对路径而不是文件的 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 );
于 2013-11-03T07:55:49.963 回答