Skip to content

magento 2.4 product collection filter by custom attribute value instead of id

Via backend, I added a dropdown custom attribute on my products. Now I need to filter the product collection based on the value of this dropdown. If I add the option id in the filter, everything works, but if I use the option value, then the filter doesn’t work:


$attributeCode = "color";
$optionId      = 5;     // $product->getColor();
$optionValue   = "Red"; // $product->getAttributeText();

$product = $this->productCollectionFactory->create()
    ->addAttributeToFilter($attributeCode, $optionId)    // this works
;

$product = $this->productCollectionFactory->create()
    ->addAttributeToFilter($attributeCode, $optionValue) // this doesn't work
;

Problem: I have the values, not the ids.. is there a way I can filter the product collection using the option values instead of the option id?