cancel
Showing results for 
Search instead for 
Did you mean: 

Custom Product Collections

Custom Product Collections

Hi,

I'm using 2.4 and I'm looking to filter a product collection with a certain attribute(s). 

For example - show all products that are black or show all products that are square etc. Is there no search query or filter to do this?

I had to create categories for this in Magento 1, Black category, Square category etc. I can't find a way to filter all products in this way, only within an existing catagory.

Thank you.

2 REPLIES 2

Re: Custom Product Collections

Hi @christopher_oliver 

 

Try to use below code:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollection = $objectManager->get("Magento\Catalog\Model\Product")->getCollection();
$productCollection->addAttributeToSelect("color")->addAttributeToFilter(
    array(
        array('attribute'=> 'color','notnull' => true),
        array('attribute'=> 'color','neq' => ''),
        array('attribute'=> 'color','neq' => 'NO FIELD'),
    ),'','left'
);
$productIds = array();
foreach ($productCollection as $product) {
    $productIds[] = $product->getId();
}
print_r($productIds);

It may help you!
Problem Solved? Please click on 'Kudos' & Accept as Solution!

Problem solved? Click Accept as Solution!

Re: Custom Product Collections

Thanks for the reply, where would this be used? Is the only way to filter products programatically like this?