0

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/… – 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
1

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

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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