7

I can get gallery images on product-list page using below code:

<?php
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $product = $objectManager->create('Magento\Catalog\Model\Product')->load($_product->getId());        
    $images = $product->getMediaGalleryImages();
    foreach($images as $child){ ?>
        <img src="<?php echo $child->getUrl(); ?>" >
<?php } ?>

I know load model in loop is bad practice and it effect to performance.Can anyone please suggest me best way to achieve same function.

3 Answers 3

1

=> Use this code. It maybe helpful to you.

<?php
$product->getMediaGalleryImages();

foreach($images as $child)
 { ?>

"<?php echo $child->getPath(); ?>
"<?php echo $child->getUrl(); ?>

}
1
use Magento\Catalog\Model\Product\Gallery\ReadHandler as GalleryReadHandler;

public function __construct(
    ...
    GalleryReadHandler $readHandler
    ...
)
{
    ...
    $this->readHandler = $readHandler;
    ...
}

/**
 * @param $product
 */
public function addGallery($product)
{
    $this->readHandler->execute($product);
}

and in your phtml

<?php foreach ($_productCollection as $_product): ?>
<?php $helper->addGallery($_product); ?>
<?php $gallery = $_product->getMediaGalleryImages(); ?>
...
<?php endforeach; ?>

Hope it helps. Also, please don't use the Object Manager directly, it's absolutely against the best practices, instead create your own helper or whatever and use dependency injection as shown in my example.

0

You can try following things.

$product->getMediaGallery('images')

Or

$product->getMediaGalleryEntries():

Your Answer

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

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