magento 2 load product collection by category id code example
Example 1: magento2 get product collection
_productCollectionFactory = $productCollectionFactory;
parent::__construct($context, $data);
}
public function getProductCollection()
{
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->setPageSize(10); // fetching only 10 products
return $collection;
}
}
?>
/*Display product collection in phtml file
Print out the product collection in phtml file with the below code:*/
list.phtml
$productCollection = $block->getProductCollection();
foreach ($productCollection as $product) {
print_r($product->getData());
echo "
";
}
Example 2: magento load product by id
$productId = 20;
$product = Mage::getModel('catalog/product')->load($productId);