Menu Close
    Hire Us Request Quote Reading List Switch to Dark Mode

    Product Collection by categories magento2

    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.

    . . .

    Comments (2)

    Add Your Comment

  • jafar
    how to get most selling product from category
  • Navin Bhudiya
    How to apply AND condition
    Let me explain in details.
    i want product that have 1,2,3 Categories mens , list of all product with same category. above code not work for this logic
  • Back to Top
    css.php
    Hire Us!
    Brief us about your requirements and we'll get back to you.
    Woo! Hooy!
    We have just recieved your project brief and our expert will contact you shortly.
    Send Again
    Close