How to Call All Products of a Specific Category in Magento 2?

  • author-img Nidhi Arora
  • 5 years
  • 525 views
How to Call All Products of a Specific Category in Magento 2?

It often happens that you need to verify the counts of products assigned to a particular category, or to fetch all the products of a category on a particular template. Then, how to call all products of a specific category in Magento 2? However, when it comes to the case of Magento 1, the answer is surely there and you know that answer very well.

But, here we are talking about Magento 2 and you know that Magento 2 comes with a new & quite different code base, so what is a nice way to call all products of a category in Magento 2?

Let’s help you to get the products of a specific category:

Step 1:

Inside the block directory of your module add the file with the following code:

<?php
namespace Envision\Eecom\Block;

class MyCategoryproduct 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 getMyCategoryProduct($categoryId)
{
$category = $this->categoryFactory->create()->load($categoryId)->getProductCollection()->addAttributeToSelect('*');
return $category;
}
}

Step 2:

So the second step is to call the function from the block file in your .phtml file:

$categoryId = 5;
$getAllProudctcollection = $block->getMyCategoryProduct($categoryId);

<ul class="category-products">
<?php
foreach ($getAllProudctcollection as $product) : ?>
<li class="level0-child">
<a href="<?php echo $product->getProductUrl(); ?>">
<?php echo $product->getName();?>
</a>
</li>
<?php endforeach;?>
</ul>

Hope it helps you. Moreover, we at Envision Ecommerce are always open to your feedbacks, suggestions and tips. If you still have any query regarding how to call products of a category in Magento 2, our certified Magento specialists are always ready to serve you!

Download Blog

ENQUIRY

Ready to Get started

Communication is the key for us to understand each other. Allow us to understand
your requirements or queries. Present us with an opportunity to serve you.

Fill out the form and out team will get back to you
within 24 hours

    Head Office

    1250 Pittsford Victor Road Ste 310
    Pittsford, NY 14534

    Development Center

    Plot no. 10, Rajiv Gandhi
    Chandigarh Technology Park