Magento – Get product collection based on custom attribute (drop down attribute value)

attributesmagento2product-collectionproducts

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
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('sku', '24-MB01')
    ->load();

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

$productcollection = $this->_productCollection
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('tag', 'popular')
    ->load();

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

Best Answer

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

So your code is like below.

$productcollection = $this->_productCollection
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('tag', 28)
    ->load();

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

enter image description here