To Retrieve Media Images Roles type from the Product in Magento 2 is useful to know each image role whether its small_image, thumbnail, or swatch image.
When you create a product, you need to assigned roles based on its display position.
The Base
Role will be displayed on the product detail page.
A small
Role will be displayed on the category listing page.
The Thumbnail
Role will be displayed on the Shopping Cart page.
Swatch image
Role will be displayed on the product swatches.
<?php namespace Jesadiya\ImageRoles\Block; use Magento\Catalog\Api\Data\ProductInterface; use Magento\Catalog\Api\ProductRepositoryInterface; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\View\Element\Template; use Magento\Framework\View\Element\Template\Context; use Psr\Log\LoggerInterface; class ImageRole extends Template { /** * @var LoggerInterface */ private $logger; /** * @var ProductRepositoryInterface */ protected $productRepository; public function __construct( Context $context, ProductRepositoryInterface $productRepository, LoggerInterface $logger, array $data = [] ) { parent::__construct($context, $data); $this->productRepository = $productRepository; $this->logger = $logger; } /** * get image roles type of each * image on the product * * @param string $sku * @return array */ public function getImageRoles($sku): array { try { $product = $this->productRepository->get($sku); } catch (NoSuchEntityException $e) { $this->logger->error($e->getMessage()); } $mediaGallery = $product->getMediaGallery('images'); $images = $this->findImageRoles($product, $mediaGallery); return $images; } /** * find image roles of each image * for the products * * @param ProductInterface $product * @param array $images * @return array */ private function findImageRoles(ProductInterface $product, array $images): array { $imagesWithRoles = []; foreach ($images as $image) { if (!isset($image['types'])) { $image['types'] = []; if (isset($image['file'])) { foreach (array_keys($product->getMediaAttributes()) as $attribute) { if ($image['file'] == $product->getData($attribute)) { $image['types'][] = $attribute; } } } } $imagesWithRoles[] = $image; } return $imagesWithRoles; } }
Call method with from the template file,
$sku = "24-MB04"; $images = $this->getImageRoles($id); foreach ($images as $image) { $types[] = $image['types']; }
An Output look likes,
Array ( [0] => Array ( [0] => image [1] => small_image [2] => thumbnail ) [1] => Array ( ) )
When you explore Product with SKU 24-MB04
, two images are assigned to this item in Magento Open source Sample data, Based on the roles assigned to each item, you can get results for the above code.
The first Image has assigned three roles and the second image has none of the Roles assigned.