How to upload to wordpress programmatically - saving files issue
Asked Answered
C

3

5

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?

Commissar answered 16/8, 2013 at 14:51 Comment(0)
L
11

use this code 100% work

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

          ?>
Lagas answered 3/7, 2019 at 5:52 Comment(0)
E
8

While I don't have a fix for your specific problem, I see what you are trying to accomplish and and I would suggest an alternate method using the Wordpress API media_handle_sideload() or media_sideload_image() functions to put the image files into the Media Library and attach them to posts automatically.

So instead of :

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

You could use:

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

That will upload the image to the Media Library as an attachment to the post and then you can make it a "Product Image" by:

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

Epirus answered 16/12, 2013 at 20:21 Comment(0)
B
6

wp_insert_attachment doesn't move the files anywhere. You must move them yourself to the correct folder. From the WordPress Function Reference: "Use absolute path and not the URI of the file. The file MUST be on the uploads directory."

I recommend using the wp_upload_bits function for moving the file since the function knows if your blog is set for yearly/montly directories, and it gives you the path and the URL of the file:

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

In your $attachment array, use ['guid'] => $upload['url'], then:

$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 );
Benefit answered 3/11, 2013 at 7:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.