Get/Load product by sku – Magento 2
Get product by SKU using product repository
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
protected $_productRepository; /** * Constructor * * @param \Magento\Framework\View\Element\Template\Context $context * @param array $data */ public function __construct( \Magento\Catalog\Api\ProductRepositoryInterface $productRepositoryInterface, \Magento\Framework\View\Element\Template\Context $context, array $data = [] ) { $this->_productRepository = $productRepositoryInterface; parent::__construct($context, $data); } public function getProductBySku($sku) { return $this->_productRepository->get($sku); } |
In phtml we can call like
1 2 3 4 5 6 |
<h3>Get product by sku 24-WB04</h3> <?php $sku = "24-WB04"; $product = $block->getProductBySku($sku); echo __($product->getName()); ?> |
Product repository get() method will …
Read More