How to Get Product Images in Magento 2
Product images and videos describe a product in a detailed manner when offered online. These files help bridge the gap between offline and online store when it comes to user assurance and satisfaction.
Hence, one cannot skip displaying the product images in an online selling platform. For example, if you are offering your store products in the Facebook shop, make it a point to display all the product images and videos in the Facebook too even if they are displayed in your store.
For Magento 2 store owners, if you are integrating such selling platforms like Facebook, etc. for offering the store products, you need to fetch all the images by loading the product and get images based on product ID or SKU.
However, if you use $product->getData(‘image’) you’ll only get the base image.
If you want to get all the product images in Magento 2, you need custom code.
Below is the programmatic method to get product images in Magento 2:
Method to Get Product Images in Magento 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?php namespace Vendor\Extension\Helper; use Magento\Framework\App\Helper\AbstractHelper; use Magento\Framework\App\Helper\Context; use Magento\Store\Model\StoreManagerInterface; use Magento\Catalog\Model\Product; class Data extends AbstractHelper { protected $productModel; public function __construct( Context $context, Product $productModel ) { $this->productModel = $productModel; parent::__construct($context); } public function getAllImages($productId) { $allImages = []; $product = $this->productModel->load($productId); $images = $productModel->getMediaGalleryImages(); foreach ($images as $image) { if (isset($image['url']) && $image['url'] !== '') { $allImages[] = $child->getUrl(); } } return $allImages; } } |
Any doubts about this solution to get product images? If so, feel free to mention them in the Comments section below.
I’d be glad to help you out.
But if you simply want to skip this part of implementing the above code for selling Magento 2 store products in Facebook, opt for Magento 2 Facebook Store Integration extension that will do the entire job for you!
The extension synchronizes the Magento 2 store products with Facebook shop to sell on Facebook.
Also, do not forget to share the post with Magento Community via social media.
Thank you.
Also Read:
Chandresh Chauhan
He has been with Meetanshi for more than three years now as a certified Magento developer. A silent guy whom you can always find solving clients' issues, is an avid reader too.
2 Comments
This doesn’t work for me. I get “Undefined variable $productModel in on line 24”
Hey Christopher,
Please try the below given code,
$images = $product->getMediaGalleryImages();