4

I am loading a product like so:

$product = Mage::getModel('catalog/product')->loadByAttribute('sku', 'MyStockCode');   

Then I try to get the images using:

$existingGallery = $product->getMediaGallery('images');   

but it comes back with a null value. When inspecting _data against $product the media_gallery attribute is missing.

From all the references I have read, this is how to load the images against a product but this doesn't seem to be working for me.

Notes:

I can see the images in the admin area against that product so they are definitely there.

I am doing this in the admin area, not frontend.

webnoob
  • 987
  • 3
  • 15
  • 26

2 Answers2

23

If you load the product by ID the media gallery will be loaded:

$product = Mage::getModel('catalog/product');
$id = $product->getIdBySku($sku);
$product->load($id);

The difference is that loadByAttribute loads the product via a collection. Alternatively, if you already have a loaded product and simply want to load the associated images, you can use

$product->getResource()->getAttribute('media_gallery')
    ->getBackend()->afterLoad($product);

After that all images of the product are accessible via $product->getMediaGalleryImages()

Vinai
  • 14,014
  • 2
  • 42
  • 83
-2

Another approach thats works too:

$product = Mage::getModel('catalog/product')->loadByAttribute('sku', 'MyStockCode'); 
$product->load('media_gallery'); //just add this line of code before you fetch gallery images
$existingGallery = $product->getMediaGalleryImages(); 
MagePsycho
  • 4,742
  • 4
  • 34
  • 64
  • It seems to be working even if you write $product->load();. Is it equivalent or does it something smart like loading just the attribute if you specified a valid one? Or does it just reload the product? In which case it's probably better to just do $p = Mage::getModel('catalog/product');$p->load($p->getIdBySku('MyStockCode')). – Nadir Sampaoli Aug 06 '14 at 08:29