Filter Product Collection for Multi Select Attribute in Magento

I came across this very interesting issue, when i was trying to filter product collection with value from Multi Select Attribute created, as it didn’t work as easy as it works for any other attribute, i.e.,

$product_collection->addAttributeToFilter('attribute_code',"some value")

The collection filters provides a filter condition finset, which helps us to filter attribute values inside a set.

First, we need to fetch the IDs for attribute’s various values, as follows:

$attributeOptionArray=array();
$opts_attr = Mage::getModel('eav/config')->getAttribute('catalog_product', 'attribute_code');
foreach ( $opts_attr->getSource()->getAllOptions(true, true) as $option){
$attributeOptionArray[$option['value']] = $option['label'];
}

Next we need to use this array of attribute values to filter across the product option:

$product_collection=Mage::getModel("catalog/product")->getCollection();
$product_collection->addAttributeToFilter("attribute_code",array('finset'=>array_search("Some Option's label",$attributeOptionArray)));

Explanation:

1. First, we load the product collection to a variable

2. We add “attributeToFilter“, in order to specify the filtering conditions.

3. With the array_search condition, we try to find the id corresponding to Option’s label.

4. Pass this id to filter with finset condition.

Advertisements

9 thoughts on “Filter Product Collection for Multi Select Attribute in Magento

    • Ideally this should go to a block which would be called from a template, providing you the required data. But this would depend on the purpose of filtering multi-select attribute.

  1. I am struggeling for about 10 hours now.

    What I am trying to accomplish:

    The simple php code to display the selected LABELS and VALUES of a multiselect product attribute in list.phtml

    I want to use the LABEL as icon image title and the VALUE as the actual image source.

    I have search Google and tried many many ways. But nothin is exactly what I need.

    Can you please please help me out?

    • Could you let me know, what are you referring to as VALUES and LABELS??
      Are you suggesting that each image would have same title for the store visitor is currently on?

    • Hello Ibrahim,
      I would be glad help you out, but need more than just the pastebin to understand what is the output you seek.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s