cancel
Showing results for 
Search instead for 
Did you mean: 

MAGENTO 2 - GET PRODUCT COLLETION BY CATEGORY

MAGENTO 2 - GET PRODUCT COLLETION BY CATEGORY

I need to list products by category. Exists someone Plugin or module for to make this? Or someone sollution in the code? Help-me, please!

3 REPLIES 3

Re: MAGENTO 2 - GET PRODUCT COLLETION BY CATEGORY

protected $_productCollectionFactory;
  
    public function __construct(       
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory
    )
    {    
        $this->_productCollectionFactory = $productCollectionFactory;
    }
    
    
    public function getProductCollectionByCategories($ids)
    {
        $collection = $this->_productCollectionFactory->create();
        $collection->addAttributeToSelect('*');
        $collection->addCategoriesFilter(['in' => ids]);
        return $collection;
    }

 

 Pass the categories ids as an array example category for dress its Id is 5 then you will call the function as

$categoriesIds = array(5);
$this->getProductCollectionByCategories($categoriesids);

Re: MAGENTO 2 - GET PRODUCT COLLETION BY CATEGORY

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();
$categoryFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory');

$categoryId = 4; // YOUR CATEGORY ID
$category = $categoryFactory->create()->load($categoryId);

$categoryProducts = $category->getProductCollection()
    ->addAttributeToSelect('*');

foreach ($categoryProducts as $product) {
    // get Product data
    print_r($product->getData());

    echo $product->getName();
}

Re: MAGENTO 2 - GET PRODUCT COLLETION BY CATEGORY

To get the product collection by Category id you need to follow the below code...

 

<?php
namespace Company\Module\Block;
Class Products extends \Magento\Framework\View\Element\Template
{
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,        
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory
    ) {
       $this->productCollectionFactory = $productCollectionFactory;
        parent::__construct($context);
    }

public function getProductCollectionByCategories($id) {
    $collection = $this->productCollectionFactory->create();
    $collection->addAttributeToSelect('*')->addCategoriesFilter(['in' => id]);
     return $collection;
}
}
?>

Thanks.