In this post I am going to explain how to get all images of product by product id in Magento 2.
1. Using Dependency Injection
Add below code snippet in Block class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | protected $_productFactory; public function __construct( \Magento\Backend\Block\Template\Context $context, \Magento\Catalog\Model\ProductFactory $productFactory, array $data = [] ) { $this->_productFactory = $productFactory; $this->_storeManager = $storeManager; parent::__construct($context, $data); } public function getProductImages($productId) { $_product = $this->_productFactory->create()->load($productId); $productImages = $_product->getMediaGalleryImages(); return $productImages; } |
Add below code snippet in template file.
1 2 3 4 5 6 7 8 9 | //Your Product ID $productId = 9; // Get Product Images $productImages = $block->getProductImages($productId); foreach ($productImages as $image) { echo $image->getUrl() . "<br/>"; } |
2. Using Object Manager
1 2 3 4 5 6 7 8 9 10 11 12 13 | $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); //Your Product ID $productId = 9; $productFactory = $objectManager->get('Magento\Catalog\Model\ProductFactory')->create()->load($productId); // Get Product Images $productImages = $productFactory->getMediaGalleryImages(); foreach ($productImages as $image) { echo $image->getUrl() . "<br/>"; } |
Leave a Reply