Magento: Filter Configurable Product by Child Product’s Attribute

This article shows how you can filter child products associated with a configurable product by the child product’s attribute value.

Suppose, we have a configurable product with two attributes (‘size‘ and ‘color‘) and we want to select only those child products with certain size and/or certain color. Let’s say, we want to select only those products that have color as ‘Red‘.

We can do so with the following code:

If we already have the value of color ‘Red‘, we can skip to next step/code. Otherwise, if we only have the name of the color then we first need to find out the value ID of that color.


$attributeCode = 'color';
$attributeValue = 'Red';

$attribute = Mage::getSingleton('eav/config')->getAttribute('catalog_product', $attributeCode);
if ($attribute->usesSource()) {
	$options = $attribute->getSource()->getAllOptions(false);
}

$attributeValueId = 0;
foreach ($options as $option) {
	if ($option['label'] == $attributeValue) {
		$attributeValueId = $option['value'];
	}
}

Next, we load our configurable product and then fetch all the child products associated with that configurable product. While fetching child products, we add a filter to the collection where we specify the attribute code (color) and value id of the color to filter.


$productId = YOUR_CONFIGURABLE_PRODUCT_ID; // ID of configurable product

$product = Mage::getModel('catalog/product')->load($productId);

$childProducts = Mage::getModel('catalog/product_type_configurable')						
						->getUsedProductCollection($product)
						->addAttributeToSelect('*')
						->addAttributeToFilter($attributeCode, $attributeValueId);

We can print and check the result:


foreach ($childProducts as $cp) {
	echo $cp->getSku() . ' ' . $cp->getColor() . ' ' . $cp->getSize(); echo '<br>';
}

Hope this helps. Thanks.