Programmatically setting images as thumbnails in Magento

Here's how to programmatically set uploaded images as a product's thumbnail, small image, and large image.

<?php
require_once 'app/Mage.php';
Mage::app();
mysql_connect(localhost, DATABASE_USER, DATABASE_PASSWORD);
mysql_select_db(DATABASE_NAME) or die("Unable to select database");
$result = mysql_query("SELECT * FROM `catalog_product_entity_varchar` WHERE attribute_id in (74,75,76) AND value='no_selection'");
while ($row = mysql_fetch_array($result)) {
$id = $row["entity_id"];
$product = Mage::getModel("catalog/product")->load($id);
$mediaGallery = $product->getMediaGallery();
if ($mediaGallery["images"][0]["file"] != '' || $mediaGallery["images"][0]["file"] != NULL) {
$path = $mediaGallery["images"][0]["file"];
$update_result = mysql_query("UPDATE `catalog_product_entity_varchar` SET VALUE='".$path."' WHERE attribute_id in (74,75,76) and entity_id=".$id);
echo "set images for product ".$id."<br />";
}
}
?>

2 comments:

  1. You can avoid writing to the database directly like this:$prod->setMediaGallery(array('images' => array(), 'values' => array()));$prod->addImageToMediaGallery($image_path, array('thumbnail'), false, false);the other input strings are 'image' for the base image, and 'small_image' for the small image. http://docs.magentocommerce.com/Mage_Catalog/Mage_Catalog_Model_Product.html#...

    ReplyDelete
  2. Aaron Lifton8/02/2010 4:23 PM

    @Jordan wow I had no idea it was so simple, I tried using the media gallery methods but I had no luck, and I couldn't find anything in the Magento documentation, thanks a lot for the comment!In my method the input strings correspond with the attribute_ids of 74, 75, and 76 so I did it that way, as I couldn't find image and small_image keys in the convoluted database structure

    ReplyDelete