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>
$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);
1 view0 comments

Recent Posts

See All

Magento 2 CMS block with the same ID already exists

I have seen the below error when I open cms block grid something went wrong with processing the default view and we have restored the filter to its original state. I found the below log in the excepti

How to generate bearer token - Magento 2 REST API

We can generate the admin bearer token using the below command. Please run the below command in the terminal to generate a token. curl -XPOST -H 'Content-Type: application/json'

Magento 2 script tag and available options in layout xml

We can add a script via layout XML file in Magento 2. The below format will stop the HTML parse until js downloaded and executed. <script src="Bilal_Usean/js/sample.min.js" /> The below format will st