Magento: Get all products by attribute id and attribute option

This article shows how to get / filter products based on it’s attribute id, or the attribute’s options id.

Get all products by a single attribute option id

Suppose, we have an attribute named ‘manufacturer’. Let’s say, this attribute has options like Samsung, Apple, Nokia, HTC, etc.
Each option has certain ID.

Suppose, we want to get all products that have manufacturer as Samsung. Let’s suppose, the option ‘Samsung’ in manufacturer attribute has ID 237.

Here is the code to get all products which has Samsung has the manufacturer.


$attributeOptionId = 237; 
$attributeCode = 'manufacturer';
 
$products = Mage::getModel('catalog/product')
					->getCollection()
					->addAttributeToSelect('*')
					->addAttributeToFilter($attributeCode, $manufacturerId);

// show only enabled products
Mage::getSingleton('catalog/product_status')
			->addVisibleFilterToCollection($products);

// show only visible products			
Mage::getSingleton('catalog/product_visibility')
			->addVisibleInCatalogFilterToCollection($products);
			 
// print all products' name
foreach ($products->getItems() as $product) {
	echo $product->getName() . '<br />';
}

Get all products for all options of the attribute

Suppose, we want to get all the products that have any of the attribute option value set. For example, we might want all products that have ‘manufacturer’ attribute set to some option value.

For this, we first have to load the attribute and get all it’s options. Convert the attribute option id-value array into an array of option id only. And, then we can use the IN SQL query to fetch the products.


$attributeCode = 'manufacturer';

// load attribute
$attribute = Mage::getSingleton('eav/config')->getAttribute('catalog_product', $attributeCode);

// get option id and label array
if ($attribute->usesSource()) {	
	$options = $attribute->getSource()->getAllOptions(false);
}

// get option id array
$optionIds = array_map(function ($ar) {return $ar['value'];}, $options);

$products = Mage::getModel('catalog/product')
					->getCollection()
					->addAttributeToSelect('*')					
					->addAttributeToFilter($attributeCode, array('in' => $optionIds));

// show only enabled products
Mage::getSingleton('catalog/product_status')
			->addVisibleFilterToCollection($products);

// show only visible products			
Mage::getSingleton('catalog/product_visibility')
			->addVisibleInCatalogFilterToCollection($products);
			 
// print all products' name
foreach ($products->getItems() as $product) {
	echo $product->getName() . '<br />';
}

Hope this helps. Thanks.