1

SOLVED (See my answer below)


How can I display product base image in .phtml template file?

$relatedProducts = $product->getProduct()
        ->getRelatedProductCollection()
        ->addAttributeToSelect(['price','name','image','status']);

Can I put addAttributeToSelect to use for this?

I found this in one other post, but it doesn't work (I put it in Block/Product.php and called it in view/frontend/templates/related_products.phtml , the getImage() part doesn't get added to URL):

public function getProductImageUrl()
{
    return $this->_storeManager->getStore()
        ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . 'catalog/product' . $this->getImage();
}

3 Answers 3

1

This worked for me:

public function getProductImageUrl($product)
{
    return $this->_image->init($product, 'product_base_image')->constrainOnly(FALSE)
                ->keepAspectRatio(TRUE)
                ->keepFrame(FALSE)
                ->getUrl();
}
0

You could create your block:

<?php

namespace Vendor\Module\Block;

use Magento\Framework\View\Element\Template;

class Newproducts extends Template
{
    private $_productFactory;

    public function __construct
    (
        Template\Context $context,
        \Magento\Catalog\Model\ProductFactory $productFactory,
        array $data
    )
    {
        parent::__construct($context, $data);

        $this->_productFactory = $productFactory;
    }

    public function getProductRelated($prodId)
    {
        $product = $this->_productFactory->create();
        $product->load($prodId);

        $collection = $product
            ->getRelatedProductCollection()
            ->addAttributeToSelect(['price','name','image','status']);

        return $collection;
    }
}

and then call block method in your template phtml:

<ul>
        <?php foreach ($block->getProductRelated($prodID) as $product): ?>
                <li><?php echo $product->getImage() ?></li>
        <?php endforeach; ?>
</ul>
1
  • where to create this block ?
    – Learner
    Commented Jan 18, 2018 at 8:20
0

Get product image from Product in PHTML file for Magento 2

$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$imageHelper  = $_objectManager->get('\Magento\Catalog\Helper\Image');
<?php $image_url = $imageHelper->init($product, 'product_base_image')->setImageFile($product->getFile())->resize($imagewidth, $imageheight)->getUrl(); ?>

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.