Quantcast
Channel: Webkul Blog
Viewing all articles
Browse latest Browse all 5490

Product Collection by categories magento2

$
0
0

Magneto-Code-Snippet

Here we are discussing how to get the collection of products assigned to any categories.

To get product collection you can use following code:

<?php

namespace Webkul\Test\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
 	/**
 	 * @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
 	 */
	protected $_productCollectionFactory;

	public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory
    ) {
        parent::__construct($context);
        $this->_productCollectionFactory = $productCollectionFactory;
    }
	public function getProductCollectionByCategories()
	{
		$categories = [2,3,5];//category ids array
	    $collection = $this->_productCollectionFactory->create();
	    $collection->addAttributeToSelect('*');
	    $collection->addCategoriesFilter(['in' => $categories]);
	    return $collection;
	}
}

Here, $categories is an array, which include category ids.

$_productCollectionFactory is an object of product collection factory which is used to get collection of product model.

addCategoriesFilter function to apply category filter.

$collection returns a collection of products which are assigned in given categories.

Thank you.


Viewing all articles
Browse latest Browse all 5490

Trending Articles