I created a custom drop down attribute in Magento2 from admin. I tried to collect all associated products by using filters. I am able to filter product collection based on text field attributes, for example

$productcollection = $this->_productCollection
    ->addAttributeToFilter('sku', '24-MB01')

But when I try to filter using dropdown custom attribute value I'm getting an empty array

$productcollection = $this->_productCollection
    ->addAttributeToFilter('tag', 'popular')

How am I supposed to filter product collection using a dropdown attribute. Can someone help with this?

  • thanks for your response. i'm looking drop down attribute product collection .Exp : attribute_code (tags) type->dropdown, drop down value (popular,new ......) i need collect all the popular products in the collection. – Suresh C Feb 7 '17 at 8:51

For dropdown attribute, We can filter using dropdown option ID instead of Label.

So your code is like below.

$productcollection = $this->_productCollection
    ->addAttributeToFilter('tag', 28)

Above 28 is the ID of the popular option of tag dropdown attribute.

enter image description here


I assume the 'Tag' is your attribute you created in the admin and the value 'Popular' is a option label associated with one of the option id with attribute 'Tag' not the value itself. The value might be an integer number internally used by magento.

As per the answer here : Loading a product collection by a specific attribute drop-down value , It is not possible to filter collection based on the option label, however you can filter the collection based on attribute option id, i.e. the integer value. You can get the option id for an option label, in your case 'popular' from the model.

You can use the code from the answer in the link I mentioned above. I hope it helps you.

PS: I did not add this answer in comment simply because I CAN NOT. I do not have enough reputation to comments. So, instead of down voting for posting an answer instead of comment, post requirement at meta stack exchange to give ability to comment with lower reputation.

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.