Magento – Getting full image URL of product in template

imagemagento2producttemplate

I'm trying to create a static block for showing dynamic products. This is code that is supposed to get every child category and print the image for each product in each category.

<?php
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $category = $objectManager->get('Magento\Framework\Registry')->registry('current_category');
    ?><ol><?php
    foreach ($category->getChildrenCategories() as $child_category) {
        ?><li>
            <ul><?php
                foreach ($child_category->getProductCollection() as $product) {
                    ?><li><img src="<?php echo $product->getImage();?>"/><li><?php
                }
            ?></ul>
        </li><?php
    }
    ?></ol>

It is almost working except for the img srcs are only "/a/b/ab001.jpg" as an example and not the full path e.g. "/pub/media/catalog/product/cache/1/small_image/240×300/abc123def456/a/b/001.jpg" so the images cannot be found. What is the correct way of getting product images?

Best Answer

If your block extends Magento\Catalog\Block\Product\AbstractProduct, you can use:

$imageType = 'category_page_list'; // choose which image
$image = $block->getImage($product, $imageType);

Then either get the image URL with

$image->getImageUrl();

or if you want to output it as <img> element:

echo $image->toHtml();

If your block does not / cannot extend the abstract product block, you can create a getImage() method on your own:

public function getImage($product, $imageId)
{
    return $this->imageBuilder->setProduct($product)
        ->setImageId($imageId)
        ->create();
}

$this->imageBuilder has to be injected as Magento\Catalog\Block\Product\ImageBuilder


The $imageType or $imageId variables should be one of the image types defined in the theme, for example category_page_list.

See app/design/frontend/Magento/luma/etc/view.xml for all image types in the Luma theme, for example.

In Magento 2 these image types are used instead of defining width and height directly in the template.

Related Topic