Magento 2 product count by attribute

Today we talk about how in Magento 2 product count by attribute. This tutorial included get product count by product attribute values. Following this example you can get count product by any attribute. For using this example you just need to replace you_attribute_code with you attribute code i.e color. So let start with our example.

    protected $_productCollectionFactory;
    protected $attributFactory;
    protected $eavConfig;

    public function __construct(
   
        \Magento\Catalog\Model\ResourceModel\Product $productFactory,
        \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\CollectionFactory $attributFactory,
        \Magento\Eav\Model\Config $eavConfig,

       
    ) {
   
        $this->eavConfig = $eavConfig;
        $this->attributFactory = $attributFactory;
        $this->_productCollectionFactory = $productFactory;            

    }


    public function getProductCountByAttributeCode()
     {
        $attributeCode = ‘you_attribute_code’;
        $attribute = $this->eavConfig->getAttribute('catalog_product', $attributeCode);
        $attributFactory = $this->attributFactory->create()->setStoreFilter(0, false);
         $itemCollection = $this->_productCollectionFactory;
        $attributFactory->getSelect()
        ->joinLeft(
            array('value_table' => $itemCollection->getTable('catalog_product_entity_int')),
            'main_table.option_id=value_table.value AND main_table.attribute_id=value_table.attribute_id', 'entity_id')
        ->reset(\Zend_Db_Select::COLUMNS)
        ->columns(array('main_table.option_id',new \Zend_Db_Expr('COUNT(value_table.entity_id)')))
        ->where('main_table.attribute_id=:attribute_id')
        ->group('main_table.option_id');
        $result = $itemCollection->getConnection()->fetchPairs(
        $attributFactory->getSelect(), array('attribute_id' => $attribute->getId()));
        return $result;        
    }

Note: Using above example you can count product by any attribute.

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

2 thoughts on “Magento 2 product count by attribute

Leave a Reply