Magento – Magento2 Custom Media Image Attribute do not work in Frontend

magento2

i have a problem by getting a custom image in the frontend.

  1. I have a custom media product attribute "image_productlist"
  2. In my product import i fill the mediaGallery like this:

$oTargetProduct->addImageToMediaGallery($aMediaData['overview_image'], ['image_productlist', 'swatch_image'], false, true);
$oTargetProduct->save();

Where $aMediaData['overview_image'] has the MEDIA IMPORT PATH AND THE FILENAME!

  1. After the import i see in my Admin Backend this image in the gallery and the flags 'image_productlist', 'swatch_image' marked at this image.

  2. Now i want to get this image with flag: 'image_productlist' in my frontend block.

For this i do something like this:

// get the variant images

$existingMediaGalleryEntries = $_simpleProduct->getMediaGalleryEntries();
foreach ($existingMediaGalleryEntries as $key => $entry) {
var_dump($entry->getData());
}

I get this list of the images in the gallery but there is no FLAG 'image_productlist'.

What is wrong??

Thanks for help.

Best Answer

Make sure the attribute is setup correctly and that the attribute setting Used in product listing is set to Yes under Storefront Properties. Then you can get a custom product image attribute by:

$imageHelper = $this->helper('Magento\Catalog\Helper\Image');

$attributeImage = $_product->getCustomAttribute('image_productlist');
$attributeImageUrl = $imageHelper->init($_product, 'image_productlist')->setImageFile($attributeImage->getValue())->getUrl();
Related Topic