As a Magento 2 developer, you know that some coding is inevitable for successful store operations. There are many tasks you need to do programmatically, especially when it comes to getting some information like customer data and customer ID or config value.
One of them also is getting product by SKU in Magento 2. And in this article, you'll learn more about two possible ways of doing that.
Post Contents [hide]
Get Product by SKU Using Dependency Injection
Dependency injection is one of the most common solutions when it comes to getting product by SKU in Magento. It's quite simple, yet no less effective.
So, to apply the dependency injection method, go to your phtml block file and create a _construct function:
public function __construct(
$this->productRepository = $productRepository;
public function getProductBySky($sku)
Now you can get the product by SKU in the phtml file:
<?php $product = $block->getProductBySky($productSku); ?>
Get Product by SKU Using Object Manager
Object Manager is one more option for you to consider. You can use it the following way:
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get(Magento\Framework\App\State::class);
$productRepository = $objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$productSku = '24-MB05';
$product = $productRepository->get($productSku);
Feel free to choose the method you prefer and get the product by SKU in Magento 2 with little to no effort.
Of course, there are many more examples where coding has to be applied. Each situation requires a different set of commands. It's obviously hard to keep all of them in mind. So you need to have a list of useful Magento 2 commands at hand.