2

I have created a brand.phtml file in my custom theme. I want to write the code for getting products having specified attribute value.

1
2
$collection = Mage::getModel('catalog/product')->getCollection()
        ->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
        ->addMinimalPrice()
        ->addFinalPrice()
        ->addTaxPercents()
        ->addUrlRewrite()
        ->addAttributeToFilter('attribute_code', 'attribute_value')
;

Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($collection);
Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($collection);

Now you should have all the active and visible products in the $collection variable

5
  • its not working
    – Asha
    Mar 5 '15 at 9:07
  • what happens?. Also make sure that you attribute is marked as "used in product listing".
    – Marius
    Mar 5 '15 at 9:14
  • <?php $collection = Mage::getModel('catalog/product')->getCollection() ->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes()) ->addMinimalPrice() ->addFinalPrice() ->addTaxPercents() ->addUrlRewrite() ->addAttributeToFilter('brand', array('eq' => 'Sony')) ;
    – Asha
    Mar 5 '15 at 9:38
  • instead of Sony you have to use the brand value id
    – Marius
    Mar 5 '15 at 9:44
  • @Marius your last two lines of code are deprecated! Status and visibility are not added anymore to the collection, quoted out in their belonging functions.
    – Jeroen
    Mar 11 '15 at 21:56
1
$sAttributeName = 'brand';
$mOptionValue = 'Sony';
$collection = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToSelect('*')
    ->addFieldToFilter(
        $sAttributeName,
        array(
            'eq' => Mage::getResourceModel('catalog/product')
                        ->getAttribute($sAttributeName)
                        ->getSource()
                        ->getOptionId($mOptionValue)
        )
    );

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.