I am developing a custom module with a custom block which displays a list a products.
This is my Block class:
use \Magento\Framework\View\Element\Template;
class Products extends Template
{
protected $_productCollectionFactory;
/**
* @param \Magento\Backend\Block\Template\Context $context
* @param \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory
* @param array $data
*/
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
array $data = []
)
{
$this->_productCollectionFactory = $productCollectionFactory;
parent::__construct($context, $data);
}
public function getHomeProducts()
{
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->setPageSize(6);
return $collection;
}
}
This is the .phtml file:
<?php
$productCollection = $block->getHomeProducts();
?>
<?php if($productCollection->count() > 0) : ?>
<div class="lrnt_hp_products">
<ul>
<?php foreach ($productCollection as $product) : ?>
<li>
<a href="<?php echo $product->getProductUrl(); ?>">
<img src="<?php echo $block->getUrl('pub/media/catalog') . 'product' . $product->getImage(); ?>" alt="<?php echo $product->getName(); ?>" />
</a>
<h2><a href="<?php echo $product->getProductUrl(); ?>"><?php echo $product->getName(); ?></a></h2>
// here I would like to print the price
</li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
I am trying to show product price in the phtml file. I can not find a way to properly show the price.
I now I can print it with
$product->getPrice()->getPrice('final_price')->getValue()
but I am searching whih automatically prints the final_price, the special price if present, ecc...
How can I achieve this?