We will be looking into how you can load product from product ID and SKU both with the help of some simple codes that are also recommended by Magento.
Let’s first look at how you can load products from product ID.
Method – 1:
<?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 getProductDataUsingId($productid) {
return $this->productrepository->getById($productid);
}
}
PHTML file code,
$product = $block->getProductDataUsingId(50);
echo $product->getName();
Method – 2:
$productid = 50;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Catalog\Api\ProductRepositoryInterface')->getById($productid);
How to load products by product SKU ::
Method – 1:
<?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);
}
}
PHTML file code,
$product = $block->getProductDataUsingSku(“productsku”);
echo $product->getName();
Method – 2:
$productsku = "productsku";
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Catalog\Api\ProductRepositoryInterface')->get($productsku);
Using these codes, you will be able to load product information by ID or SKU.
Thanks.