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
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
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();
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!
In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…
In the world of business, understanding financial metrics is crucial for making informed decisions and…
Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…
In this era, businesses are always on the lookout for ways to engage with their…
Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…
E-commerce has transformed the way consumers shop for products and services and interact with businesses.…