I'm trying to load the product images of related products on the category list.phtml without loading the complete product model (to increase performance).
My current code in list.phtml
is this:
<?php $relatedProducts = $_product->getRelatedProducts(); ?>
<?php if(!empty($relatedProducts)): ?>
<div class="left-carousel">
<div class="product-small-thumbs">
<div class="carousel carousel-<?php $_product->getId()?>">
<?php $i = 0 ?>
<?php foreach($relatedProducts as $relatedProduct): ?>
<?php $i++ ?>
<?php if($i < 5): ?>
<div class="slide">
<?php
$relatedProductId = $relatedProduct->getId();
$relatedProduct = $block->getProductById($relatedProductId);
$resizedImageBig = $block->resizeImage($relatedProduct, 'product_base_image', 460, 460)->getUrl();
$resizedImageSmall = $block->resizeImage($relatedProduct, 'product_base_image', 90, 90)->getUrl();
$relatedProductUrl = $relatedProduct->getUrlKey();
?>
<img data-id="smallthumbs-<?php echo $_product->getId();?>"
data-img="<?php echo $resizedImageBig; ?>" data-img_def=""
src="<?php echo $resizedImageSmall; ?>"/>
</div>
<?php endif; ?>
<?php endforeach; ?>
</div>
</div>
Notice the getproductbyId function which loads the complete product:
public function getProductById($id)
{
return $this->_productRepository->getById($id);
}
Is there away to avoid loading the complete product? I think that my current code is bad for performance. The preferred way would be to only load the resized/cached product main image.
Solution I've used @Sohel Rana answer to solve this problem and this worked very good. However this didn't give me the resized/cached images, so I used a separate module for this: staempfli/magento2-module-image-resizer
You can find it here: https://packagist.org/packages/staempfli/magento2-module-image-resizer
Final code:
<?php $resizerHelper = $block->getImageResizerHelper(); ?>
<?php $relatedProducts = $_product->getRelatedProducts(); ?>
<?php if(!empty($relatedProducts)): ?>
<div class="left-carousel">
<div class="product-small-thumbs">
<div class="carousel carousel-<?php $_product->getId()?>">
<?php $i = 0 ?>
<?php foreach($relatedProducts as $relatedProduct): ?>
<?php $i++ ?>
<?php if($i < 5): ?>
<div class="slide">
<?php
$relatedProductId = $relatedProduct->getId();
$images = $block->getImageFromDB($relatedProductId);
$first_image = $images[0]['image'];
$first_image_url = $block->getFullImageUrl($first_image);
$resized_image_large = $resizerHelper->resizeAndGetUrl($first_image_url, 460, 460);
$resized_image_small = $resizerHelper->resizeAndGetUrl($first_image_url, 90, 90);
$relatedProductUrl = $relatedProduct->getUrlKey();
?>
<img data-id="smallthumbs-<?php echo $_product->getId();?>"
data-img="<?php echo $resized_image_large ?>" data-img_def=""
src="<?php echo $resized_image_small ?>"/>
</div>
<?php endif; ?>
<?php endforeach; ?>
</div>
</div>