Magento – Magento 2 Get all product images in on product list page

imagemagento2mediaproductproduct-images

In Magento 1 I've always used

$_product->getMediaGallery('images')

But in the source from Magento 2 I see

$productImage = $block->getImage($_product, $image);
echo $productImage->toHtml();

It's only getting the first product image. How do I get the second or third image (not only the base one)?

GetMediaGallery function doesn't exists?

Update:
$_product->getMediaGalleryImages() throws NULL in a var_dump

and

for getMediaGallery and getMediaGalleryEntries I get the same notice error:

Undefined property: Magento\Catalog\Model\Product\Interceptor::$getMediaGallery

Best Answer

Category loading has changed in 2.1, so this may only be relevant from 2.1 onwards:

The image gallery is added to the product via an extension interface defined via di.xml. The upshot is that we can manually create an instance of the gallery ReadHandler class and pass a product to load all its gallery images.

As usual in Magento 2 the best way to instantiate a class is via the __construct() method, so here is a stub block class:

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

class Gallery
{
    protected $galleryReadHandler;

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

    /** Add image gallery to $product */
    public function addGallery($product)
    {
        $this->galleryReadHandler->execute($product);
    }
}

In your template, assuming you have $product loaded via a product collection, you would be able to call:

$block->addGallery($product);
$images = $product->getMediaGalleryImages();
foreach ($images as $image) {
    ...
}
Related Topic