14

How to get all products of category using category id in magento 2?

Rakesh Jesadiya
  • 42,221
  • 18
  • 132
  • 183

5 Answers5

28

you can inject in your block an instance of \Magento\Catalog\Model\CategoryFactory like this:

protected $categoryFactory;
public function __construct(
    ....
    \Magento\Catalog\Model\CategoryFactory $categoryFactory,
    ...
){
    ...
    $this->categoryFactory = $categoryFactory;
    ...
}

Then create this method in your block:

public function getCategory()
{
    $categoryId = $this->getCategoryId();
    $category = $this->categoryFactory->create()->load($categoryId);
    return $category;
}
public function getProductCollection()
{
     return $this->getCategory()->getProductCollection()->addAttributeToSelect('*'); 
}

Then you can use in the template this:

<?php foreach ($block->getProductCollection() as $product) : ?>
    <!-- do something with $product -->
<?php endforeach;?>

You should be able now to just add this to your homepage content

{{block class="Block\Class\Name\Here" category_id="5" template="path/to/template.phtml"}}
Marius
  • 197,939
  • 53
  • 422
  • 830
  • In implementing this solution i ran into the same problem posted about here: http://magento.stackexchange.com/questions/123374/module-created-gives-error-filtering-template-classname-does-not-implement-bl I'm adding this in so if others need further clarification on how to use this solution, they have one stop shopping. – circlesix Aug 11 '16 at 17:00
  • @Marius is there any way to do it via the repository pattern i.e., via the service contracts provided by Magento? – Mathanagopal S Mar 15 '20 at 05:43
2

You need to replace getProductsCollection() by getProductCollection() (without s)

7ochem
  • 7,532
  • 14
  • 51
  • 80
1

I am using this

echo '('.$subcat->getProductCollection()->count().')';

foreach ($subcats as $subcat) { 
    if ($subcat->getIsActive()) {
        $_category = $objectManager->create('Magento\Catalog\Model\Category')->load($subcat->getId());
        $_imgUrl = $_category->getImageUrl(); 
        $subcat_url = $subcat->getUrl();
        // echo $qty = $subcat->getQty(); exit;
        $subcat_img = $store->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . 'catalog/category/' . $subcat->getImage(); 
        $placeholder_img = "pub/media/placeholder.png";
        if($_imgUrl ==''){
            $_imgUrl = $store->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA)."catalog/category/placeholder.png";
        }
        ?>
        <div class="col-sm-2 item-two">
            <a href="<?php echo $subcat_url; ?>">
                <div class="item-two-img">
                    <img src="<?php echo $_imgUrl; ?>" class="img-responsive"/>
                </div>
                <p><?php echo $subcat->getName(); 
                    $subcat->getProductCollection()->count(); ?>
                    <span class="pro_quantity">
                        <?php echo '('.$subcat->getProductCollection()->count().')';?>
                    </span>
                </p>
            </a>
        </div>
        <?php
    }
}
sv3n
  • 11,657
  • 7
  • 40
  • 73
venkata prasad
  • 535
  • 13
  • 38
1

You can use addCategoriesFilter function. With this function you filter by several category ids.

First you need inject CollectionFactory:

protected $_productCollectionFactory;

public function __construct(
    ....
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
    ...
){
    ...
    $this->_productCollectionFactory = $productCollectionFactory;
    ...
}

Then somewhere in the code:

public function getCollectionByCategoryId($id)
{
    $ids = [$id];
    $collection = $this->_productCollectionFactory->create();
    $collection->addAttributeToSelect('*');
    $collection->addCategoriesFilter(['in' => ids]);

    return $collection;
}
karick
  • 171
  • 2
  • 3
1

Better and more actual way to get products by category - via ProductRepository and built-in Filters (from Magento 2.2)

public function __construct(
    ProductRepositoryInterface $productRepository,
    SearchCriteriaBuilder $criteriaBuilder
) {
    $this->productRepository = $productRepository;
    $this->criteriaBuilder = $criteriaBuilder;
}

/**

  • @return ProductInterface[]

*/ public function getProducts(): array { $categoryIdsToExport = $this->config->getCategoriesToExport();

return $this-&gt;productRepository-&gt;getList(
    $this-&gt;criteriaBuilder
        //It's Custom Filter from Magento_Catalog::di.xml
        -&gt;addFilter('category_id', $categoryIdsToExport, 'in') 
        //Here you cat filter products in standart Magento way
        -&gt;addFilter('status', \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
        -&gt;addFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
        -&gt;create()
)-&gt;getItems();

}

Unfortunately There are few info in stackexchange about "Search Criteria Unify Processing" - better and currently proper way to filter,sort models.

Here Magento doc about Search Criteria Unify Processing

Also you can register your own CustomFilter to filter products. See example in vendor/magento/module-catalog/etc/di.xml :

<virtualType name="Magento\Catalog\Model\Api\SearchCriteria\CollectionProcessor\ProductFilterProcessor" type="Magento\Eav\Model\Api\SearchCriteria\CollectionProcessor\FilterProcessor">
    <arguments>
        <argument name="customFilters" xsi:type="array">
            <!-- You can specify your attribute and map a class to apply filter -->
            <item name="category_id" xsi:type="object">Magento\Catalog\Model\Api\SearchCriteria\CollectionProcessor\FilterProcessor\ProductCategoryFilter</item>
            <item name="store" xsi:type="object">Magento\Catalog\Model\Api\SearchCriteria\CollectionProcessor\FilterProcessor\ProductStoreFilter</item>
            <item name="store_id" xsi:type="object">Magento\Catalog\Model\Api\SearchCriteria\CollectionProcessor\FilterProcessor\ProductStoreFilter</item>
            <item name="website_id" xsi:type="object">Magento\Catalog\Model\Api\SearchCriteria\CollectionProcessor\FilterProcessor\ProductWebsiteFilter</item>
        </argument>
    </arguments>
</virtualType>
Ruslan Mavlyanov
  • 380
  • 1
  • 13