Hello Magento Friends,
Today I am here with a common yet important solution for all of you. How To Load Products By SKU In Magento 2.
Loading products helps to get product information. Getting product information is important to perform product-related operations. Product SKU (Stock Keeping Unit) is a unique value that is used to identify a product. You can load products by SKU in Magento 2 to get product information.
Let’s look at the steps to Load Products By SKU In Magento 2
Steps to Load Products by SKU in Magento 2:
Method 1:
Using root Script. Create productloadbysku.php in magento root directory and add below code.
<?php use Magento\Framework\AppInterface; try { require_once __DIR__ . '/app/bootstrap.php'; } catch (\Exception $e) { echo 'Autoload error: ' . $e->getMessage(); exit(1); } try { $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER); $objectManager = $bootstrap->getObjectManager(); $appState = $objectManager->get('\Magento\Framework\App\State'); $appState->setAreaCode('frontend'); $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $productsku = "productsku"; // add Your SKU here $product = $objectManager->get('\Magento\Catalog\Model\ProductRepository')->get($productsku); print_r($product->getSKU()); } catch(\Exception $e) { print_r($e->getMessage()); }
After adding code run below URL for testing.
https://yourdomain.com/productloadbysku.php
Method 2:
Step 1: Create Product.php file in below path
app\code\Vendor\Extension\Block\
And add below code.
<?php namespace Vendor\Extension\Block; class Product extends \Magento\Framework\View\Element\Template { protected $productrepository; public function __construct(\Magento\Catalog\Api\ProductRepositoryInterface $productrepository) { $this->productrepository = $productrepository; } public function getProductDataUsingSku($productsku) { return $this->productrepository->get($productsku); } }
Step 2: Add below code in your PHTML file
$product = $block->getProductDataUsingSku(“productsku”); echo $product->getName();
Conclusion:
Hence, this way you can Load Products by SKU in Magento 2. You can also Load Products by Product ID in Magento 2. In case you have any queries, mention them in the comment part. For more Magento solutions, keep updated with us regularly.
Happy Reading!