0

How to get Product id and Sku By using the product Name in a phtml file?

Teja Bhagavan Kollepara
  • 3,816
  • 5
  • 32
  • 69
SUBIN CHANDRAN
  • 350
  • 4
  • 19
  • Please search before posting question https://magento.stackexchange.com/questions/94851/magento2-how-to-load-product-by-id – Vishwas Bhatnagar Jul 27 '17 at 10:23
  • @Vishwas Bhatnagar if you know the answer post the answer..i have been searching for long and did not find an answer.. i need this in a phtml file..by using the "product name".. – SUBIN CHANDRAN Jul 27 '17 at 10:38
  • 3
    @Vishwas Bhatnagar Can you tel me where is the duplicate here ? he want to get the product by name and not by ID ! – PЯINCƎ Jul 27 '17 at 10:57
  • 1
    @SUBINCHANDRAN please see Siarhey Uchukhlebau answer , it should work for you . Name is never a unique identifier two products can have same name , so loading product by name might give unreliable results – Vishwas Bhatnagar Jul 27 '17 at 12:02

2 Answers2

4

In the .phtml template you can use only the ObjectManager to get desired result:

<?php
$productNameHere = 'Aim Analog Watch';
//Get Object Manager Instance
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
/** @var \Magento\Catalog\Api\ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->get('Magento\Catalog\Api\ProductRepositoryInterface');
/** @var \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $objectManager->get('Magento\Framework\Api\SearchCriteriaBuilder');
$searchCriteria = $searchCriteriaBuilder->addFilter('name', $productNameHere)->create();
/** @var \Magento\Catalog\Api\Data\ProductInterface[] $items */
$items = $productRepository->getList($searchCriteria)->getItems();

or you should do it in the block (not in template, because its recommended as better solution).

Siarhey Uchukhlebau
  • 15,957
  • 11
  • 54
  • 83
-1

Well, I haven't done it before, but I think first you will need to load the product by name and then get the product id and SKU. This can be done via Factory Method:

<?php

  protected $product;  


  public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Model\ProductFactory $product

    ) {
        $this->product = $product;
        parent::__construct($context);
    }

    public function getProduct($name)
    {
        return $this->product->create()->load($name);
    }

}

Now call the getProduct function in your phtml file like this:

$productName = "product_name"; //Product Name
$product=$this->getProduct($productName);

echo $product->getId(); //Get Product ID

I hope this would help you.

Fayyaz Khattak
  • 2,102
  • 2
  • 18
  • 26