I am new to magento2, I don't know how to get the product images by their role and display it on the frontend. can anyone help me to understand this flow from scratch, so I can understand how to interact with the backend images and it will help me a lot.

For Example: I have role attributes like on_hover, on_animation, and on_gif.

2 Answers 2


You can get types of gallery images of a product by following code:

  $existingImage = $product->getMediaGalleryEntries();

  foreach ($existingImage as $image) {


you can get it by below code :

  $baseImage  = $product->getImage();
  $smallImage = $product->getSmallImage();
  $thumbnail  = $product->getThumbnail();

For your custom attribute role :

$customIcon = $product->getResource()->getAttribute('Your_attribute_name')->getFrontend()->getValue($product);

for show it in frontend :

$img = $product->getResource()->getAttribute($imageCustomRole)->getFrontend()->getValue($product);
if($img) {
     $productImageAttr = $product->getCustomAttribute($imageCustomRole);
     $productImage = $this->imageHelper->create()->init($product, $imageCustomRole)
     $result = $productImage->getUrl();
  1. Create a media type attribute for the product and assign it to the default attribute group. see the screenshot.

Attibute create

enter image description here

enter image description here

  1. Inside the code part where you want to featch OR display these images.
    $_helper = $this->helper('\Magento\Catalog\Helper\Image');
    $_product = $block->getProduct();
    $hoverUrl = $_helper->init($_product, 'on_hover')->setImageFile($_product->getOnHover())->getUrl();
    $animationUrl = $_helper->init($_product, 'on_animation')->setImageFile($_product->getOnAnimation())->getUrl();
    $gifUrl = $_helper->init($_product, 'on_gif')->setImageFile($_product->getOnGif())->getUrl();
  • Error: Call to undefined method Magento\Catalog\Helper\Output::init() in /var/www/html/theme/app/design/frontend/Ewall/UltraClean/Magento_Catalog/templates/product/list.phtml:82 getting this error Jul 20, 2022 at 6:31
  • First, if you are going to fetch images over the PLP page, then you have to assign images like gif, animation, hover, etc., for specific products from Admin. Then, you have to place code inside the foreach loop. Please see this URL - tinyurl.com/2a87bhfq
    – Dotsquares
    Jul 20, 2022 at 6:42
  • You have to override the view.xml file in your custom theme structure. Hope this will help from my side. Follow this URL black.bird.eu/en/blog/image-hover-magento-2.html
    – Dotsquares
    Jul 20, 2022 at 7:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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