This article shows how to load product by id and sku in Magento 2.
We will be using Magento 2’s Service Layer for this task. Use of Service Layer is highly encouraged by Magento.
Below is a block class of my custom module (Chapagain_HelloWorld). I have injected object of \Magento\Catalog\Model\ProductRepository class in the constructor of my module’s block class.
app/code/Chapagain/HelloWorld/Block/HelloWorld.php
<?php
namespace Chapagain\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
protected $_productRepository;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Catalog\Model\ProductRepository $productRepository,
array $data = []
)
{
$this->_productRepository = $productRepository;
parent::__construct($context, $data);
}
public function getProductById($id)
{
return $this->_productRepository->getById($id);
}
public function getProductBySku($sku)
{
return $this->_productRepository->get($sku);
}
}
?>
Now, we load the product by id and sku in template file.
$id = YOUR_PRODUCT_ID;
$sku = 'YOUR_PRODUCT_SKU';
$_product = $block->getProductById($id);
$_product = $block->getProductBySku($sku);
echo $_product->getEntityId();
echo '<br />';
echo $_product->getName();
Using Object Manager
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$appState = $objectManager->get('\Magento\Framework\App\State');
$appState->setAreaCode('frontend');
$productRepository = $objectManager->get('\Magento\Catalog\Model\ProductRepository');
$id = 1; // YOUR PRODUCT ID;
$sku = '24-MB01'; // YOUR PRODUCT SKU
// get product by product id
$product = $productRepository->getById($id);
// get product by product sku
$product = $productRepository->get($sku);
Hope this helps. Thanks.