Magento 2 product collection filter by attribute

Today we discuss how in Magento 2 product collection filters by attribute. We take the example of product collection and filter it by given size. So here is our example.

protected $_productCollectionFactory;
public function __construct(
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productFactory
    ) {
         $this->_productCollectionFactory = $productFactory;
    }
    public function getProductCollection()
    {
        $productCollection = $this->_productCollectionFactory->create();
        $productCollection->addAttributeToFilter('size',  array('notnull' => true));

        return $productCollection;
     
     }

Note: You can sort any collection following this example.

Search

Recent Blogs

Categories

Archives

Archives

Tags