3

Is it possible to have the product image url loaded as part of the product collection?

for examples:

Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*');

This doesnt add the image.

3 Answers 3

10

Do it as such:

$collection = Mage::getModel('catalog/product')->getCollection();

$backendModel = $collection->getResource()->getAttribute('media_gallery')->getBackend();

foreach($collection as $product){
    $backendModel->afterLoad($product); //adding media gallery to the product object
    var_dump($product->getData()); //you should see media gallery information here now
}

This loads the backend model and appends the media gallery attribute for the $product in the loop instead of re-loading the entire product model.

2
  • Since this the go-around method for loading the whole product, does it have any set back in performance? Commented Apr 30, 2015 at 0:43
  • Using this code, I get Fatal error: Call to a member function getId() on null in /srv/ambushco-/app/code/core/Mage/Catalog/Model/Resource/Product/Attribute/Backend/Media.php on line 76 Whether I call load() on the collection or not, it results in the same error.
    – ahnbizcad
    Commented Dec 8, 2016 at 1:11
3

These worked for me

$collection = Mage::getModel('catalog/product')
                ->getCollection()
                ->addAttributeToSelect('image');

foreach($collection as $product){
    (string)Mage::helper('catalog/image')->init($product, 'image');
    //Or with resize
    (string)Mage::helper('catalog/image')->init($product, 'image')->resize(200);
}
1
  • but what about other images on the same product?
    – ahnbizcad
    Commented Dec 8, 2016 at 1:13
2

I think you should be able to access the image URL from the product such as:

$collection = Mage::getModel('catalog/product')->getCollection();

foreach ($collection as $product) {
   echo $product->getImageUrl();
}
1
  • but what about other images on the same product?
    – ahnbizcad
    Commented Dec 8, 2016 at 1:13

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.