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);

About Bilal

I'm a software programmer, I handle Magento2 modifications at any level.

View all posts by Bilal →

Leave a Reply

Your email address will not be published. Required fields are marked *