1

How to get product by name? I have the name of the product in my code and iIwant to get product so I use this code :

$model = Mage::getModel('catalog/product');
$product = $model->load('name-of-product','product_name');   

To get product but it return a null object(Mage_Catalog_Model_Product) iIuse this code for other models and it worked but for 'catalog/product' not working. How to get product?

2 Answers 2

2

Try this

$product = Mage::getModel('catalog/product')->loadByAttribute('name', $productName); 

Note: Make sure your name attribute code is proper.

In addition

loadByAttribute() basically loads the product collection and filter those collection by attribute you have specified and then it is returns the collection first item.

$collection = $this->getResourceCollection()
    ->addAttributeToSelect($additionalAttributes)
    ->addAttributeToFilter($attribute, $value)
    ->setPage(1,1);
2
  • thank u it worked !! Commented Aug 22, 2017 at 5:45
  • Does not work for me on Magento 1.9.4
    – Black
    Commented May 9, 2019 at 10:14
1

Try this, Hope it's helpful to you.

$products = Mage::getModel('catalog/product')
                    ->getCollection()
                    ->addAttributeToFilter(
                        array(
                            array('attribute' => 'name', 'like' => '%'.$search.'%')
                        )
                    )
                    ->getFirstItem();
3
  • thanks for your answer but return null object Commented Aug 22, 2017 at 5:47
  • check it updated answer....it is working.. Commented Aug 22, 2017 at 5:56
  • Instead of load() use getFirstItem() so it returns only the first result
    – Mr. Lewis
    Commented Aug 22, 2017 at 6:34

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.