Magento – Magento-2 get product collection from category id on home page

category-products

$categoryId = '3';
    $objectManager =  \Magento\Framework\App\ObjectManager::getInstance();
    $categoryFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory');
    $productFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
    $category = $categoryFactory->create()->load($categoryId);
    $collection = $productFactory->create();
    $collection->addAttributeToSelect('*');
    $collection->addCategoryFilter($category);
    $collection->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
    $collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)->load();
    $collection->setPageSize(5);

    foreach($collection as $products){
        print_r($products->getData());
    }

Best Answer

Use this code in your block :

<?php

namespace CompanyName\ModuleName\Block;

class HelloWorld extends \Magento\Framework\View\Element\Template

{    

    protected $_categoryFactory;

        

    public function __construct(

        \Magento\Backend\Block\Template\Context $context,        

        \Magento\Catalog\Model\CategoryFactory $categoryFactory,

        array $data = []

    )

    {    

        $this->_categoryFactory = $categoryFactory;

        parent::__construct($context, $data);

    }

    

    public function getCategory($categoryId) 

    {

        $category = $this->_categoryFactory->create();

        $category->load($categoryId);

        return $category;

    }

    

    public function getCategoryProducts($categoryId) 

    {

        $products = $this->getCategory($categoryId)->getProductCollection();

        $products->addAttributeToSelect('*');

        return $products;

    }

}

?>

Now, Get data in phtml file

$categoryId = 6;

$categoryProducts = $block->getCategoryProducts($categoryId);

foreach ($categoryProducts as $product) {
    print_r($product->getData());
}

Using Object Manager :

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();        

$categoryFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory');

$categoryHelper = $objectManager->get('\Magento\Catalog\Helper\Category');

$categoryRepository = $objectManager->get('\Magento\Catalog\Model\CategoryRepository');

$categoryId = 6;

$category = $categoryFactory->create()->load($categoryId);
$categoryProducts = $category->getProductCollection() ->addAttributeToSelect('*');
foreach ($categoryProducts as $product) {
    print_r($product->getData());
}

Hope this helps. Thanks.

Note :- Do not use Object Manager Directly.

Related Topic