Magento – Get configurable product options and attributes

Getting all options of a specific attribute in Magento is fairly easy:

1
2
3
4
$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', 'color'); 
foreach ($attribute->getSource()->getAllOptions(true) as $option) {
    echo $option['value'] . ' ' . $option['label'] . "\n";
}


A more challenging task is to get the options and values that are applicable to a particular configurable product. This can solved using the following code:

1
2
3
4
5
6
7
8
// Collect options applicable to the configurable product
$productAttributeOptions = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product);
$attributeOptions = array();
foreach ($productAttributeOptions as $productAttribute) {
    foreach ($productAttribute['values'] as $attribute) {
        $attributeOptions[$productAttribute['label']][$attribute['value_index']] = $attribute['store_label'];
    }
}

The resulting array will consist of an associative array, indexed by the attribute label, with nested arrays containing attribute value => attribute label items.
Something like:

1
2
3
4
5
6
7
8
9
10
11
12
$attributeOptions = array(
    'Color' => array(
         1 => 'Green',
         2 => 'Orange',
         ...
    ),
    'Size' => array(
        6 => 'L',
        7 => 'XL',
        ...
    ),
);
Advertisements