get product by id magento 2 code example

Example 1: magento 2 get loaded product by id

$om = \Magento\Framework\App\ObjectManager::getInstance();
$product = $om->create('Magento\Catalog\Model\Product')->load($id);

Example 2: 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 3: magento load product by id

$productId = 20;
$product = Mage::getModel('catalog/product')->load($productId);

Tags:

Misc Example