Black Friday & Cyber Monday - Up to 100% Off Explore

How to get product by id and sku in magento 2

Getting product id and sku in Magento 2 brings you the exact ID number and SKU which are corresponding to the item you want to find. All things you have to do are using the following commands in the admin console of your magento 2 store. Mageplaza makes a great effort to write this topic, and I hope it will help you be clear to know how to get the product id and sku in Magento 2.

Overview of getting product by id and sku in Magento 2

  • Step 1: Declare the command to get product id and sku
  • Step 2: Load product id and sku in template file

Step 1: Declare the command to get product id and sku

You will use a block class of the module Mageplaza_HelloWorld, then possibly inject the object of \Magento\Catalog\Model\ProductRepository class in the constructor of the module’s block class.

app/code/Mageplaza/HelloWorld/Block/HelloWorld.php

<?php
namespace Mageplaza\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{	
	protected $_productRepository;
		
	public function __construct(
		\Magento\Backend\Block\Template\Context $context,		
		\Magento\Catalog\Model\ProductRepository $productRepository,
		array $data = []
	)
	{
		$this->_productRepository = $productRepository;
		parent::__construct($context, $data);
	}
	
	public function getProductById($id)
	{
		return $this->_productRepository->getById($id);
	}
	
	public function getProductBySku($sku)
	{
		return $this->_productRepository->get($sku);
	}
}
?>

Step 2: Get product id and sku in template file

Next, please use the below script to get the product by id and sku in the template file.

$id = YOUR_PRODUCT_ID;
$sku = 'YOUR_PRODUCT_SKU';
$_product = $block->getProductById($id);
$_product = $block->getProductBySku($sku);
echo $_product->getEntityId();
echo '<br />';
echo $_product->getName();

If you have any queries about the article or any questions in general, use the comment section below!





Enjoyed the tutorial? Spread it to your friends!

magento-2-tutorial
get
product
id
sku

Comments for How to get product by id and sku in magento 2

Please leave comments if you have any questions, feedbacks.

Module Development

You also may like these Magento 2 Extensions

One Step Checkout

$199
10 reviews

Layered Navigation

$99
12 reviews

SEO

FREE
no review

Shop By Brand

$99
3 reviews

People also searched for:

  • magento 2 get product by id and sku
  • load product by id and sku in magento 2
  • magento 2 product by id and sku
  • magento 2 load product by id and sku
  • how to get magento 2 product by id and sku
  • how to load product by id and sku in magento 2