I need somehow to get id of product right after it addition to gallery of product, i am trying this code, but still ID is null for some reason:

        array('image', 'small_image', 'thumbnail'),


$items = $product->getMediaGalleryImages();

foreach($items as $productImage) {
    if(basename($productImage->getFile()) === basename($imageToAdd)){
        $uploadedImagesIds[] = $productImage->getId(); // it gives NULL

Althrough I've called $product->save() method it still gives me null on $productImage->getId();

Is it possible to retrieve id of image added to gallery somehow ?

1 Answer 1


Not sure if this is the problem, but I think if you call load again after calling save it might work.

So after $product->save(); do this:

$_product = Mage::getModel('catalog/product')->load($product->getId());
$items = $_product->getMediaGalleryImages();
//then your foreach loop here

Here is why I think this.

The getMediaGalleryImages method looks like this:

public function getMediaGalleryImages()
    if(!$this->hasData('media_gallery_images') && is_array($this->getMediaGallery('images'))) {
        $images = new Varien_Data_Collection();
        foreach ($this->getMediaGallery('images') as $image) {
            if ($image['disabled']) {
            $image['url'] = $this->getMediaConfig()->getMediaUrl($image['file']);
            $image['id'] = isset($image['value_id']) ? $image['value_id'] : null;
            $image['path'] = $this->getMediaConfig()->getMediaPath($image['file']);
            $images->addItem(new Varien_Object($image));
        $this->setData('media_gallery_images', $images);

    return $this->getData('media_gallery_images');

Look a the first if statement. The images are retrieved again from the db only if inside the product instance _data['media_gallery_images'] is not set or $this->getMediaGallery('images') is not an array.
Since you already called load on the product before adding the image _data['media_gallery_images'] is always set, so the code is not executed. You only get the images you previously had and the image you added.
But the image you just added does not have an id because the method that is called to actually assign the image does not return the id: Mage_Catalog_Model_Product_Attribute_Backend_Media::addImage.
Reloading the product instance again should get you the id.

Small note: I think save is not really needed, but not sure.

  • Wow, thanks so much it worked ! Tried without $product->save(); but it's not worked, so seems like this is required.
    – Ilja
    Commented Mar 10, 2016 at 10:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.