Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magento: How to programatically set the base image to the first image in the list

Tags:

image

magento

The problem

Current Situation

I'm having a problem with a third-party ioncube loader encoded feedloader plugin which is no longer supported by the original author (since they went tits-up) and instead of putting in two weeks to completely write it from scratch, I've decided to fix the problems it has after the import has run.

Compatibility

The only problem is: I want to write this using functions in the Mage library, not rely on a few custom queries that might break in the next update of Magento or whenever I change something in the database (I just want to get to know Magento's core functions better I guess)

Problem Diagnosis

The import does nearly everything correct, except from setting the base image (the small and thumbnail image are set correctly), as you can see in the screenshot below:

The first and only image has not been selected as default Base Image

The actual record in the database is missing for that image.. (so tempted to fix it with a query, but I won't.. I'm going to keep looking for an elegant solution)

Also, the function $product->getMediaGalleryImages() doesn't return any images, so I can't use the solution as suggested by @SKV over at Set Base Image Programmatically .. unless I am doing something wrong.

like image 761
Henry van Megen Avatar asked Oct 03 '13 08:10

Henry van Megen


1 Answers

$productId = 1;
//load the product
$product = Mage::getModel('catalog/product')->load($productId);
//get all images
$mediaGallery = $product->getMediaGallery();
//if there are images
if (isset($mediaGallery['images'])){
    //loop through the images
    foreach ($mediaGallery['images'] as $image){
        //set the first image as the base image
        Mage::getSingleton('catalog/product_action')->updateAttributes(array($product->getId()), array('image'=>$image['file']), 0);
        //stop
        break;
    }
}
like image 82
Marius Avatar answered Nov 13 '22 00:11

Marius