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

  • Please search before posting question magento.stackexchange.com/questions/94851/… Jul 27, 2017 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".. Jul 27, 2017 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, 2017 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 Jul 27, 2017 at 12:02

2 Answers 2


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

$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).


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:


  protected $product;  

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

    ) {
        $this->product = $product;

    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

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

I hope this would help you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.