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:Then either get the image URL with
or if you want to output it as
<img>
element:If your block does not / cannot extend the abstract product block, you can create a
getImage()
method on your own:$this->imageBuilder
has to be injected asMagento\Catalog\Block\Product\ImageBuilder
The
$imageType
or$imageId
variables should be one of the image types defined in the theme, for examplecategory_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.