In the previous post I saw you how to load product by ID?, Today in this post I will show you How to Load Product by SKU in Magento 2? This code snippet will be very helpful for developers in the custom development with Magento 2.
<?php namespace Vendor\Module\Block; class ProductData extends \Magento\Framework\View\Element\Template { protected $productRepository; public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\Catalog\Model\ProductRepository $productRepository, array $data = [] ) { $this->productRepository = $productRepository; parent::__construct($context, $data); } public function getProductBySku($sku) { return $this->productRepository->get($sku); } }
Now we can use below code in template(phtml) file to display product data by SKU.
<?php $sku = 'MB001' //Product SKU // get product by SKU $_product = $block->getProductBySku($sku); echo $_product->getId(); //Product ID echo $_product->getName(); //Product Name echo $_product->getSKU(); //Product SKU echo $_product->getPrice(); //Product Price