In this post I am going to explain how to load product by SKU in magento 2.
1. Using Dependency Injection
Add below code snippet in Block class.
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 getProductBySku($productSku)
{
return $this->_productRepository->get($productSku);
}Add below code snippet in template file.
// Your product SKU $productSku = 'PROD009'; $productData = $block->getProductBySku($productSku); echo $productData->getId() . '<br/>'; echo $productData->getName() . '<br/>'; echo $productData->getProductUrl() . '<br/>';
2. Using Object Manager
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productRepository = $objectManager->get('\Magento\Catalog\Model\ProductRepository');
// Your product SKU
$productSku = 'PROD009';
$productData = $productRepository->get($productSku);
echo $productData->getId() . '<br/>';
echo $productData->getName() . '<br/>';
echo $productData->getProductUrl() . '<br/>';Thats it. Enjoy Magento 2!!
Write an article about ecommerce that help people to grow their ecommerce business. You’ll find best ecommerce guide, news, tips & more!


May 6, 2020 at 2:17 pm
Very valuable information, keep sharing.