top of page

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

Comments


Follow Me

  • LinkedIn
  • Twitter
  • Facebook
  • YouTube
  • Instagram

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

bottom of page