Loading products by SKU & ID in Magento 2 are the most sought-after queries. The purpose is to get the product’s details to perform various operations. We have already written a tutorial on how to load product by ID in Magento 2. Here, we will see how to load product by SKU. The same idea with a different approach.
Today, we'll show you two different ways to load product by sku in Magento 2:
$sku="ABC"; $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $product = $objectManager->get('Magento\Catalog\Model\Product')->loadByAttribute('sku', $sku);
<?php namespace FME\Module\Block; class Product extends \Magento\Framework\View\Element\Template { protected $_productloader; public function __construct( \Magento\Catalog\Model\ProductFactory $_productloader ) { $this->_productloader = $_productloader; } public function getLoadProduct($sku) { return $this->_productloader->create()->loadByAttribute('sku', $sku); } }
phtml file code
$product=$this->getLoadProduct(“ABC”); echo $product->getName();
In programming, there are often different ways to get a particular result. You can get product by SKU either by Object Manager or Factory Objects. The factory method is faster and hence recommended.
If you're having issues in loading product by SKU in Magento 2, then contact our support team to get an instant solution.Check our tutorial to Get Product Collection by Category ID in Magento 2.