I am trying to filter product collection by ids if I use below code, the filter works ok and the product shows.

            ->addFieldToFilter('entity_id',array('in'=> 460 ));

The problem is that if I set an array to this code and try to filter, I keep getting empty collection.

$getData = array(460);
            ->addFieldToFilter('entity_id',array('in'=> $getData ));

I've already tried setting array like the following

$getData[$a]= array(460);

and reading like

array('in'=> $getData[$a] )

PS: My array is variable, not only one product I can't see anything wrong with the code and if dump array it is ok I think: array([0] => int(460))

  • Well, I was placing the code below this: $this->prepareSortableFieldsByCategory($layer->getCurrentCategory()); if ($origCategory) { $layer->setCurrentCategory($origCategory); } } after placing the code before this lines it works weirdly, if someone can explain, I will accept as answer. – Gabriel G May 16 '18 at 15:01
  • Please share your full collection code. Are you having this on Magento 2? – kunj May 16 '18 at 18:27
  • Please check that 460 is product's ID or category's ID. – kunj May 17 '18 at 5:20
  • It is product ID, and on magento 1.9.3. Please check my comment, any info? – Gabriel G May 17 '18 at 19:56
  • Ok, try my code and let me know if it is working for you or not. – kunj May 17 '18 at 20:12

Try this:

$getData= array(17,78);
$collection->addAttributeToFilter('entity_id',array('in'=> $getData ));

This is working for me.

|improve this answer|||||

You were doing the filter after category filter,so it may be that product is not in current category.That why your collection was returning Null. .

Better way to filter by product ids is

$productIDS =  array(460,4,98);
|improve this answer|||||
  • the products are in the category. it is like the code was not accepting an array of values after those lines of code. Check my comment. – Gabriel G May 17 '18 at 19:57

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.