Magento – How to Get Products with a Specific Attribute Value

attribute-setattributesfilterproductproduct-attribute

How can I get the products with a attribute (attribute name is "use_state") value of "new"? I added an attribute called "use_state" and an attribute set with that attribute. Then I created some products that have this attribute set and assigned value "new" to these products' "use_state" attribute. For the world, I cannot anyhow get these products in my block, in order to be able to display them. I tried these approaches and each one was just giving me some useless information that I don't even understand, instead of the concrete products information, that I actually expect from them. I tried this:

$collection = Mage::getModel('catalog/product') -> getCollection(); 
$collection -> addAttributeToSelect(array('name'));
$collection -> addFieldToFilter("use_state", "new");

print "DEV: <pre>"; print_r($collection); print "</pre>";

$_products = Mage::getResourceModel('catalog/product_collection')
->addAttributeToSelect(array('name'))
->addAttributeToFilter('use_state', 'new')
->load();

echo "DEV: <pre>"; print_r($_products); echo "</pre>";

Not giving me any products, just some info that I don't even understand. Can you help me see what's wrong here?

I have just found out that this line might be the culprit:

->addAttributeToFilter('use_state', 'new') 

, and this is because 'new' is not the value to filter by, but another, coded value, which is in my case, 234. I don't know how to translate 'new' to 234 though.

Best Answer

$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('name');  
$collection->addAttributeToSelect('price');    

//products whose price is 100

$collection->addFieldToFilter(array(
    array('attribute'=>'price','100'),
));
Related Topic