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 ]

107 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!

  18. Esan says:

    Thanks Matt very very very much

    now I have a question.
    how can multiple images upload simultaneously for a product?
    I use of “gold Cart” plugin that have possible multiple image upload.
    Thanks in advance

  19. matt says:

    Hi Esan,

    I haven’t tested it, but (in theory), if you added 3 columns to your csv and assigned each to ‘Image’, each product would have 3 images added for it. Please don’t do this on a live site, as I don’t know whether this will work or not. Let me know how you go.

  20. Esan says:

    Hi Matt,
    I used of 3 column . but It don’t work. I tested and CSV upload used only of last column of images .
    Thanks.

  21. matt says:

    Hi Esan,

    Thanks for letting me know. Thought that might have been wishful thinking. Off the top of my head, I would add the image locations separated by something, e.g. |

    image1.jpg|image2.jpg|image3.jpg etc

    I would then modify the code to explode $cvs_data2['imagename'][$i] by | and process it with a for-next loop applying the code above.

    I’m working on a plugin for wpec importing and multiple images will be included, but I have too much work on at the moment.

    sorry I cant be of more help
    cheers

    Matt

  22. Craig Parker says:

    So I import a csv to the regular specs, then create another one with three columns, edit the import.php file, and off I go?
    What would happen if I just put the image (with html code pointing at it) in the description?

  23. zhenya says:

    Thank`s, it`s work

  24. matt says:

    Hi Craig,
    Just follow the tutorial above and off you go. If the image is already on your server, you could include a html link to it if you prefer. See my response to James’ query regarding HTML above.

    Hi Zhenya,
    Glad it works.

  25. Cory says:

    This import process works great & all of my images are mapped correctly to the products.

    A problem I am running into is the single product page thumbnail width is not adhering to my settings.

    Everything has been set to 150×150, but as you can see from these examples, the images are much wider and not sticking within my dimensions.

    http://www.alltoolsinc.com/products/pliers-snips/asian-styline-dial-cutting-nippers-6-12/
    http://www.alltoolsinc.com/products/pliers-snips/14-dbl-phl-long-power-bit-1-65mml/

    Other products are sized just fine so I’m not sure what’s up.

    Any idea how to enforce the width in 3.8+ more consistently?

    Thanks,
    Cory

  26. matt says:

    Hi Cory,

    1. Are your media settings correct? (e..g in settings/media are thumbnails set to 150 x 150)
    2. Is a thumbnail being created? FTP to wherever you have uploaded your images too (by default, if uploading this month, would be SITEURL/wp-content/uploads/2012/02/), and check that there are different variations of each image there. E.g. image01.jpg, image01-150×150.jpg etc.

    If the answer to 1 and 2 are ‘Yes’ then its probably an issue with the wpec theme you are using. Try switching to the default theme and seeing if that works.

    If the answer to 1 is no, then change it.

    If the answer to 2 is no, then I will have to review the code.

    Let me know either way

    Thanks
    Matt

  27. sayed says:

    how to upload images from another website ??

  28. Mike says:

    Bummer, so you have to edit your csv to include the month\date for every item? That is a nightmare unless I am missing something.
    I am unable to get the visser plugin to work but this seems to me to be about the same as manually entering every image if you have to edit every field in your csv- am I missing something?

  29. serena says:

    I’m wondering if you have a quick (for you to post), similar solution for uploading images based on their WordPress ID? I have several hundred images already loaded into my media library that I would like to make reference to. I am using GoldCart with WPEC and with each product I’ve got the option of three additional images. I’d love to make a place for all of them based on their IDs in my CSV!

    Thank you,
    Serena

  30. matt says:

    Sayed, I think with a few minor amendments to the tutorial, you might be able to import from other sites, but I’ll have to test this when I get a chance. Alternatively, add the HTML for the image to the product description, but ensure that you remove the esc_attr function (see comments above)

    Serena, sounds fairly straightforward, I will write a solution asap.

    Mike, read Prashant’s comment (the first one) for a modification that negates the need to use month/date. I will be making use of this in my (continually-promised, never-delivered) importer plugin.

  31. serena says:

    Oh boy! Thank you so much!! :D

  32. Cory says:

    Matt,
    Thanks for your response…

    1) Yes, the media settings are set.
    2) Only 5-10 total images (not related to cart) are auto-sized to 150×150. (slider & widget images only for homepage)

    Would love to get some help… is there a plugin to go thru and auto-size & update the thumbnails or something else I can do?

    Thanks
    Cory

  33. matt says:

    Hi Cory,

    Hmm, not sure what the problem is. I will have to re-test the code to ensure that its ok from my side.

  34. Sergei says:

    Thank you!. I use it. It works. But ID’s for products auto add is only evens. Like this 2,4,6,8… It’s uncomfortable to add a products to a post for me.

  35. Sergei says:

    Oh, sorry). It’s question for developers of wp eCommerce)

  36. sayed says:

    I am using wordpress 3.3.1 and wp-ecommerce 3.8.7.5 .

    I don’t have a directory such as SITEURL/wp-content/uploads/YEAR/MONTH

    I have siteurl/wpcontent/ .. and in this directory i have themes and plugins directory.

    where should i upload images, plz help.

  37. matt says:

    Hi Sayed,

    When you first upload an image via the media section in the backend, the uploads directory should be created. Try uploading something to generate this.

  38. Dom says:

    THANK U! CAN YOU PLEASE MAKE A CSV COLUMN FOR DOWNLOADS ATTACHED TO PRODUCTS. I HAVE ADDED ALL MY DONWLOADS INTO /www/wp-content/uploads/wpsc/downloadables I NEED A FASTER/EASIER WAY WHEN USING CSV TO HAVE THEM IN THE RIGHT AREAS!!! PLEASE HELP ME!! I CAN SEND YOU A PAYPAL PAYMENT FOR UR HELP! THANKS!! ANYONE!!!

  39. rodolfo says:

    hi Guys,

    for all interested, to import multiple images (instead of one) is as simple as adding a loop in the above code. then in the csv use a delimeter such as | for adding more images.

    //adding image support

    if ( $cvs_data2['imagename'][$i] != ” ){
    //need the full location of the file so first we get the upload directory
    $upload_dir = wp_upload_dir();

    //get each image delimeted by ‘|’
    $all_images = explode(“|”, $cvs_data2['imagename'][$i]);

    foreach ($all_images as $each_image){
    //now build the file location
    $filename = $upload_dir['baseurl'] . ‘/’ . trim( $each_image );
    //we also need to store just the file location from within the upload directory
    $metafilename = trim( $each_image );
    //establish filetype
    $wp_filetype = wp_check_filetype(basename($filename), null );
    //build our attachment array
    $attachment = array(
    ‘post_mime_type’ =gt; $wp_filetype['type'],
    ‘post_title’ =gt; preg_replace(‘/\.[^.]+$/’, ”, basename($filename)),
    ‘post_content’ =gt; ”,
    ‘post_status’ =gt; ‘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 one image
    }
    // finished all images
    }

  40. matt says:

    @rodolfo – good work. Will include your code in the import plugin, thanks.

    @dom – will add it to the list

  41. Dom says:

    Hey thank a lot matt! it would really help a lot due to the fact i have 3800+ items that need downloadables attached and I’ve only did like a 100 the hard way :(

  42. sayed says:

    hello matt, all works till now,

    But I want to add some custom csv columns like,
    (Mfg part #, Our part # , Manufacturer, Short description, condition, color, etc)

    now I added each one in import.php below line#78 ie. “”

    it each option even appears in the store/import page,, but when i import it and goto products page, my customs columns don’t appear but those of wordpress default appears like, product name, price, etc… plz plzz help !!

  43. sayed says:

    and plz a little detailed , I am new to php.

  44. matt says:

    Hi Sayed, custom meta is handled the same way as normal post-meta. For the plugin I’m working on, I just added an array of custom fields and extended the import script to add them using the standard add_post_meta function. I’m afraid I don’t have the time at the moment to be more detailed than that, but I will try and get my importer plugin finished in the next 2-3 weeks. Sorry I can’t be any more helpful.

  45. Lynn says:

    Hi Matt,

    Just tried to download the imgprocess.php script but sadly getting a 404 error.
    Yes, i did remove the XXX!! :)
    Is this no longer available? It was exactly what I needed!

  46. matt says:

    Hi Lynn,

    I just right clicked the link, selected ‘save file as’ and saved it to desktop and opened it in my code editor no problem.

    Not sure if my server was playing up before, but its definitely still there.

  47. Lingerie says:

    Hi,
    don’t work for me :-(
    The import is OK but not the result.. That is strange is no GUID for image.
    The posttitle is “lubrifiant-fruity-love-orange-abricot-p-image-107084-grande-5″ (no .jpg at the end and no 2012/04/)
    an idea ?

    thanks a lot for your help

  48. matt says:

    Hi Lingerie,

    Im not sure I follow?
    Post title should be the title of the product?
    If you are talking about the image in the media manager, the 2012/04 isnt part of the title, and WordPress doesnt include the image extension in the title of the image.
    Do you have a link to where-ever your site is?

  49. Lingerie says:

    Hi,

    thanks for reply. I found my mistake, the file name was not the good :-) Sorry about that.
    I have a question for you.
    Can we import tag ? Category ? Custom Fields ? Variant ?

    regards

    Ludo

  50. matt says:

    Hi Ludo,

    Tutorial on Categories here: http://www.haycroftmedia.com/archives/307/wp-e-commerce-upload-adding-multiple-categories-to-csv-upload-updated-for-3-8#more-307

    I hope to release an importer plugin that will allow for importing of all possible WPEC fields soon, but as you will see from my comments throughout my blog, I’ve been promising this for a while and work keeps getting in the way!

    If you are comfortable with php and WP then its fairly straightforward to adapt the tutorial on categories to allow for tags. Custom fields are just normal WP post-meta fields, Variations are a bit more complex.

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