0

I'm trying to filter products by a custom attribute, but the addFieldToFilter isn't working. I get an error "Error filtering template: Warning: Illegal string offset 'attribute'"

Where am I going wrong?

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
$productCollection->addFieldToFilter(
                           array('attribute'=>'engine_store_show_on_homepage','eq'=>1)
                       );
$productCollection->load();
echo "<pre>";print_r($productCollection->getData()); //print product collection

I appreciate others have asked the same question, but I don't understand the answers given as they all require a class or module to be created. I'm trying to do this within a template .phtml file.

1

2 Answers 2

1

Hi @chirs use below code for the filter. use addAttributeToFilter Instead of addFieldToFilter

$collection->addAttributeToFilter('engine_store_show_on_homepage', ['eq' => 1]);
2
  • Thanks, unfortunately this doesn't seem to filter and returns every product still. I've tried adding $productCollection->addAttributeToSelect('*'); and the custom variable isn't returned with the results, could that be a factor?
    – Chris
    Aug 24, 2020 at 11:31
  • Strangely.. I edited the attribute in admin panel and hit save without making any changes and it is now showing that attribute on the frontend and filtering correctly. I guess the data migration tool missed something out.
    – Chris
    Aug 24, 2020 at 11:37
1

You Get Filter Following code :-

$_products->addAttributeToFilter('engine_store_show_on_homepage', array('eq' => 1)); // Using the operator
$_products->addAttributeToFilter('engine_store_show_on_homepage', 1); // Without using the operator

And check more information :-

https://fishpig.co.uk/magento/tutorials/addattributetofilter/

THANKS.

1
  • Thanks Mohit, I did look at that page before when looking for an answer. It turns out my problem was actually the attribute its self didn't migrate across from M1 properly and so my attempts to filter the results were not working until I re-saved the attribute.
    – Chris
    Aug 24, 2020 at 11:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.