Can anybody give me a hint about how to load product's media gallery along with the collection?
I'm getting the collection like this:
$collection = Mage::getModel('catalog/product')->getCollection()
->addStoreFilter($storeId)
->addAttributeToFilter('status', Mage_Catalog_Model_Product_Status::STATUS_ENABLED);
foreach ($collection as $product) {
var_dump($product->getMediaGalleryImages());
}
But getMediaGalleryImages() returns null
. I know that I can load each product separately with $product = Mage::getModel('catalog/product')->load($product->getId())
but I want to avoid this, because it causing unnecessary workload.
All you need to is inject \Magento\Catalog\Model\ProductRepository class in your construct. Using getSpecialPriceByProId($proId) function with pass product ID as Parameter, you can get the product's special price by product id.
I had to do the same recently, fastest method:
class My_Module_Block_Name extends Mage_Catalog_Block_Product_View_Abstract
{
/** @var null|Mage_Catalog_Model_Resource_Eav_Attribute */
protected static $_mediaGalleryBackend = null;
public function getGalleryImages()
{
$product = $this->getProduct();
$this->_getBackend()->afterLoad($product);
$collection = $product->getMediaGalleryImages();
return $collection;
}
/**
* @return Mage_Catalog_Model_Resource_Eav_Attribute
*/
protected function _getBackend() {
if (self::$_mediaGalleryBackend === null) {
$mediaGallery = Mage::getSingleton('eav/config')
->getAttribute(Mage_Catalog_Model_Product::ENTITY, 'media_gallery');
self::$_mediaGalleryBackend = $mediaGallery->getBackend();
}
return self::$_mediaGalleryBackend;
}
}
In case anyone’s looking for another approach on this, I found this to work (in just one case so no guarantees!):
Be sure to do $collection->addAttributeToSelect(’image’);
first, then when looping through the collection products, do:
$attributes = $product->getTypeInstance(true)->getSetAttributes($product);
$media_gallery = $attributes[’media_gallery’];
$backend = $media_gallery->getBackend();
$backend->afterLoad($product); //this loads the media gallery to the product object
Not sure if all of this is necessary but I’m in a hurry. In my particular case I was trying to get the image url using $product->getImageUrl();
and this approach worked for me.
Hope it helps someone else.
try this
$collection = Mage::getModel('catalog/product')->getCollection()
->addStoreFilter($storeId)
->addAttributeToSelect(array('image', 'media_gallery'))
->addAttributeToFilter('status', Mage_Catalog_Model_Product_Status::STATUS_ENABLED);
foreach ($collection as $product) {
var_dump($product->getMediaGallery());
}
It can be used directly in loop:
foreach ($collection as $product) { $product->getResource()->getAttribute('media_gallery')->getBackend()->afterLoad($product); foreach ($product->getMediaGalleryImages() as $image) { var_dump($image->debug()); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With