We will be using Magento 2’s Service Layer for this task. Use of Service Layer is highly encouraged by Magento 2.
Below is a block class of my custom module (Mtutorials_HelloWorld). I have injected object of \Magento\Catalog\Model\ProductRepository class in the constructor of my module’s block class.
app/code/Mtutorials/HelloWorld/Block/HelloWorld.php
_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 = 123; // YOUR PRODUCT ID $sku = 'product-sku-123'; // YOUR PRODUCT SKU $_product = $block->getProductById($id); $_product = $block->getProductBySku($sku); echo $_product->getEntityId(); echo '
'; 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 = 'product-sku-123'; // YOUR PRODUCT SKU
// get product by product id
$product = $productRepository->getById($id);
// get product by product sku
$product = $productRepository->get($sku);
Hope this will helps you!