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.

1

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

<?php
$product->getMediaGalleryImages();

foreach($images as $child)
 { ?>

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

}
0

You can try following things.

$product->getMediaGallery('images')

Or

$product->getMediaGalleryEntries():
0
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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