Get product collection by category id on phtml file magento2
You can add this in the Block, and call the function getProductCollection() in phtml,
protected $_productCollectionFactory;
protected $_categoryFactory;
public function __construct(
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
\Magento\Catalog\Model\CategoryFactory $categoryFactory,
\Magento\Framework\View\Element\Template\Context $context
) {
$this->_categoryFactory = $categoryFactory;
$this->_productCollectionFactory = $productCollectionFactory;
}
public function getProductCollection()
{
$categoryId = 'yourcategoryid';
$category = $this->_categoryFactory->create()->load($categoryId);
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addCategoryFilter($category);
$collection->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
$collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
return $collection;
}
you can simply call block and get product collection using below code,
Inside BLock file,
<?php
namespace Company\Categories\Block;
class Categoryproduct extends \Magento\Framework\View\Element\Template
{
protected $categoryFactory;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Model\CategoryFactory $categoryFactory
) {
$this->categoryFactory = $categoryFactory;
parent::__construct($context);
}
public function getCategoryProduct($categoryId)
{
$category = $this->categoryFactory->create()->load($categoryId)->getProductCollection()->addAttributeToSelect('*');
return $category;
}
}
call function in your .phtml file,
$categoryId = 5;
$getProudctcollection = $block->getCategoryProduct($categoryId);
<ul class="category-products">
<?php
foreach ($getProudctcollection as $product) : ?>
<li class="level0-child">
<a href="<?php echo $product->getProductUrl(); ?>">
<?php echo $product->getName();?>
</a>
</li>
<?php endforeach;?>
</ul>