• Bilal Malik

Get/Load product by sku – Magento 2

Get product by SKU using product repository

    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

<h3>Get product by sku 24-WB04</h3>
<?php 
$sku = "24-WB04";
$product = $block->getProductBySku($sku);
echo __($product->getName());
?>

Product repository get() method will accept the below arguments

public function get($sku, $editMode = false, $storeId = null, $forceReload = false);

Recent Posts

See All

What is requireJS AMD in Magento2

Simply we can say, below format is the AMD module. define(['jquery'] , function ($) { return function () {}; }); Module Vs AMD module 1. Javascript Module Pattern (function () { this.myGlobal =

©2020 by Bilal Usean. Proudly created with Wix.com