Blog

The Haycroft Media Blog covers all aspects of website design and development from the web browsers being used through to the standards that govern the world wide web. As a website design and development company, it is imperative that we keep abreast of all the latest news and happenings in our field, and here we present the major stories along with tutorials, tips and other web-programming related items.

wp-e-commerce upload adding images to CSV upload – updated for WPEC 3.8

We’ve covered uploading multiple categories in wp-e-commerce, but what about images?

Update: If you are using a version of WP-E-Commerce prior to 3.8 then the below should still work. If you are using 3.8 or later, please scroll down to “Version 3.8 +”

It stands to reason that if you are uploading a bunch of products, you will want images to accompany them. This takes a little more work than adding multiple categories, but is significantly easier than adding them one-by-one.

1. Preparing the Images

If you are happy doing bulk resizing/cropping in whichever graphics package you use, then do it! Process your product images so that you have a thumbnail that matches the size defined in your wp-e-commerce installation (96px X 96px is the current default).

Next process your source images again so that you have a large image that is either a manageable size, or sized to your wp-e-commerce product image size settings (128px X 128px is the current default). Once you have thumbnails and full-size images, upload the thumbnails to “wp-content/uploads/wpsc/product_images/thumbnails/” and the full-size to “wp-content/uploads/wpsc/product_images/”. You can now move onto step 2 “Importing”.

If you aren’t happy batch-processing images you can create a directory called “‘wp-content/uploads/wpsc/product_images/temp” and upload all your product images there. Please ensure that the images are at a manageable size (i.e. less than 1000px wide or high).

Next download and save a copy of the “imgprocess.php” script we cobbled together (remove the XXX from the extension) – n.b. this script is largely based on a great function here

Adjust the thumbnail size variables ($thumbwidth and $thumbheight) on lines 3-4 to correspond with the thumbnail sizes specified in wp-e-commerce (default is 96px X 96px). If you want your large images processed as well then add the relevant dimensions to the $largewidth and $largeheight variables on lines 6 and 7. Alternatively, leave them at 0 if you don’t want to resize your large images. Please note that this is a basic script so it only crops images to the exact sizes specified. If you want your large images to be scaled, you will have to add that functionality yourself.

Once you have made your adjustments, upload the script to the root of your WordPress installation (in most cases yoursite.com/imgprocess.php). Please note that this script has not been extensively tested, and you run it very much at your own risk. We highly recommend running it in a test environment first and take no responsibility for anything (from server failure to hives or plagues of locusts) that occurs from the moment you run it!!

If you chose to continue, run the script by entering the location into your browser (in most cases http://www.yoursite.com/imgprocess.php). The script will take a while to execute, but all being well you will see a big ugly message saying “Images processed”. Your thumbnails directory should now be populated with the thumbnails you created.

If you chose not to resize the large images then simply copy the images from “wp-content/uploads/wpsc/product_images/temp” to “wp-content/uploads/wpsc/product_images”. Otherwise, your resized large images should be in wp-content/uploads/wpsc/product_images/’.

Next delete “wp-content/uploads/wpsc/product_images/temp” and delete imgprocess.php.

2. Importing
Open wp-e-commerce/wpsc-admin/includes/settings-pages/import.php
locate the option list:

<option value='name'>Product Name</option>
<option value='description'>Description</option>
...etc

and add the following option value:

<option value='imagename'>Image</option>

Next locate the line

$existing_name = get_product_meta($id, 'url_name');

and add the following above it so it reads:

$image_query = "INSERT INTO `".WPSC_TABLE_PRODUCT_IMAGES."` (product_id,image ) VALUES ('$id','".$cvs_data2['imagename'][$i]."')";
$wpdb->query($image_query);
$imageid = $wpdb->get_var("SELECT LAST_INSERT_ID() as id FROM `".WPSC_TABLE_PRODUCT_IMAGES."`");
//now add image id to product
$image_query2 = "UPDATE `".WPSC_TABLE_PRODUCT_LIST."` SET image = ".$imageid." WHERE id=".$id;
$wpdb->query($image_query2);
$existing_name = get_product_meta($id, 'url_name');

Now add a column to your product list csv that you wish to upload and add the name of each image uploaded to the relevant image
e.g.
SKU, Name, Price, Image
001, Shoe, 100, shoe.jpg
002, Hat, 20, hat.jpg

Upload the csv as normal remembering to assign ‘Image’ to the relevant column, and your products should now be loaded complete with images.

VERSION 3.8 +
Version 3.8 of WP-E-Commerce makes use of the new post-types feature in WordPress. This means we can make use of some core WordPress functions to add our images.

In terms of prepping images, all that’s needed is the full size image this time, no need for a thumbnail. Once the images are ready, FTP them to SITEURL/wp-content/uploads/YEAR/MONTH where year and month are the year and month. So for right now (April 2011), this would be SITEURL/wp-content/uploads/2011/04

Next we can prepare our csv something like this:

SKU, Name, Price, Image
001, Shoe, 100, 2011/04/1.jpg
002, Hat, 20, 2011/04/2.jpg
003, Sock, 23, 2011/04/3.jpg

Take note of the fact that we include the year/month/filename structure in the csv

Now we can update import.php

First we add the option to assign the image name, so locate:

<option value='name'><?php _e('Product Name', 'wpsc'); ?></option>

and then add

<option value='imagename'>Image</option>

Now go to what will be line 162:

wp_set_object_terms( $product_id , array( (int)$_POST['category'] ) , 'wpsc_product_category' );

and add the following directly underneath:


if ( $cvs_data2['imagename'][$i] != '' ){
//need the full location of the file so first we get the upload directory
$upload_dir = wp_upload_dir();
//now build the file location
$filename = $upload_dir['baseurl'] . '/' . trim( $cvs_data2['imagename'][$i] );
//we also need to store just the file location from within the upload directory
$metafilename = trim( $cvs_data2['imagename'][$i] );
//establish filetype
$wp_filetype = wp_check_filetype(basename($filename), null );
//build our attachment array
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
);
//insert attachment data into WP IMPORTANT - we need to use $metafilename here NOT the filename with the full URL
$attach_id = wp_insert_attachment( $attachment, $metafilename, $product_id );
// you must first include the image.php file
// for the function wp_generate_attachment_metadata() to work
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
//generate metadata
$attach_data = wp_generate_attachment_metadata( $attach_id, $metafilename );
wp_update_attachment_metadata( $attach_id,  $attach_data );
//finished!

}

Now upload your csv via the import section (Settings>Store>Import) and select ‘Image’ for the image name column.
Import, and your products, complete with images, should now be present!

[ Back ]

67 Responses to wp-e-commerce upload adding images to CSV upload – updated for WPEC 3.8

  1. prashant says:

    Thanx a lot man…
    it worked for me with wp-e-commerce 3.8.6 with small addition in code…
    i have just changed $metafilename variable bcoz it was not appending the “Year/Month” in my link…
    $metafilename=substr($upload_dir['subdir'],1) . ‘/’.$metafilename;

  2. matt says:

    Thanks Prashant,

    Glad it worked. I included the year/month in the csv for the purpose of this tutorial, but your way is much better. Thanks.

  3. arkant1 says:

    It works like a charm for me. Thanks for this great tutorial !

  4. matt says:

    Good! Glad to hear it, and thanks for the feedback.

  5. James Hall says:

    Can the description field be html? i.e., would it be placed in the html tab of the prod description? Some of us have a lot of html formatting in the descriptions etc. It would be really nice if we could transfer that information ;-)

  6. matt says:

    Hi James,

    Look for these lines:


    'content' => esc_attr( $cvs_data2['description'][$i] ),
    'additional_description' => esc_attr( $cvs_data2['additional_description'][$i] ),

    and simply remove the esc_attr function to get:


    'content' => $cvs_data2['description'][$i],
    'additional_description' => $cvs_data2['additional_description'][$i],

    Be aware that this function sanitises input, so if there are stray apostrophes (‘) or speech marks (“) in your descriptions, it may break the import.

  7. James says:

    Works like a charm and you’ve saved me from having to purchase the product importer from Visser Labs.

    Thanks for taking the time to do this :)

  8. ChrisG says:

    Hi Matt

    Great tutorials, thanks for spending the time to write them all. Obviously the default importer doesnt support variations, have you had a look to see if you could modify the code to support them, and/or is this planned for your import plugin you’ve mentioned elsewhere?

    cheers
    Chris

  9. Carolette says:

    I am using wp ecommerce 3.8.7.2 and I am not sure where to apply the code. Can you help?

    Here is the code from import.php. Thanks in advance.

    false, ‘test_type’ => false );
    $_FILES['import']['name'] .= ‘.txt’;
    $file = wp_handle_upload( $_FILES['import'], $overrides );

    if ( isset( $file['error'] ) )
    return $file;

    $url = $file['url'];
    $type = $file['type'];
    $file = $file['file'];
    $filename = basename( $file );

    // Construct the object array
    $object = array( ‘post_title’ => $filename,
    ‘post_content’ => $url,
    ‘post_mime_type’ => $type,
    ‘guid’ => $url,
    ‘context’ => ‘import’,
    ‘post_status’ => ‘private’
    );

    // Save the data
    $id = wp_insert_attachment( $object, $file );

    // schedule a cleanup for one day from now in case of failed import or missing wp_import_cleanup() call
    wp_schedule_single_event( time() + 86400, ‘importer_scheduled_cleanup’, array( $id ) );

    return array( ‘file’ => $file, ‘id’ => $id );
    }

    ?>

  10. Carolette says:

    Sorry, I guess my code is above the limit. Let me know if you need to see the entire code.

    Thanks,

  11. matt says:

    James – glad to be of help.

    ChrisG, None of the e-commerce sites I’ve built have needed variations (bizarrely), so haven’t needed to play with importing them, but will take a look and look at improving the importer plugin so that it allows for this as well.

    Carolette, please read the tutorial, its as clear as it can be on what to do. Otherwise, I’m working on an importer plugin which will include image importing so check back soon and hopefully it will be available (work keeps getting in the way sadly).

  12. Kira says:

    Well done! The only thing that I had a lot of trouble with is that the importer doesn’t know about header rows, so I think that’s what caused the image to not show up. I was just trying to import one product as a test and it wasn’t working. I have added further instructions (for future users) to the import page and moved the image option to the bottom where I want it. My images are all going into /uploads/ which is just fine with me.

    This will make my job a LOT easier and the importer from the other company doesn’t even work, so I must use this one. I’m using 3.8.7.2 by the way.

    I have a question though. Does anybody know how to indicate weight unit as grams? I’ve tried Grams, grams, G and g, and no matter what it shows in the product list as 0.7g (with no space- which is wrong) and when I go in to edit the product, it shows units as Pounds. I can’t find documentation on what it’s looking for and searched the database to no avail. Any help most appreciated though this is a bit off-topic. Thank you!

  13. Kira says:

    I figured it out. I have to enter “gram” (without the quotes) as the weight unit. yay!

  14. hello,

    thank you so much for this tutorial! it is such a great help coz i will be uploading thousands of product to my site! thank you! a million thanks! :)

    Is there a way to include table rate prices? Quantity In Cart, Discounted Price?

  15. matt says:

    @Kira glad you got it sorted.

    @brando glad to be of help. There is a way to include other meta data, but I haven’t added a tutorial on this yet. Come back soon and hopefully there will be a solution!

  16. Ryan says:

    This worked like a charm!

    Is there a way to tweak this code to be able to import the “Off Site Product Link” URL?

    thanks again

  17. matt says:

    Hi Ryan,
    Glad its working for you. Its not too difficult to tweak using the example above and in my other posts on importing as a guide, but if you’re not confident playing around with the code, then you’ll have to wait until I finalise the importer plugin I’m afraid. Hopefully won’t be too long!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Facebook Comments