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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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.
1 2 3 4 5 6 7 8 | // 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
1 2 3 4 5 6 7 8 9 10 11 12 | $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!!
May 6, 2020 at 2:17 pm
Very valuable information, keep sharing.