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!
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);
$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();
}
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.