How to get configurable product options and attributes

How to get configurable product options and attributes

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

$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:

// 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:

$attributeOptions = array(
    'Color' => array(
         1 => 'Green',
         2 => 'Orange',
         ...
    ),
    'Size' => array(
        6 => 'L',
        7 => 'XL',
        ...
    ),
);

Stay tuned for more Magento code tips from Atwix developers!

Read more:

Case Studies

Meet our clients

From startups backed by Mark Cuban and Sir Richard Branson, to some of the biggest eCommerce operations in the world, Atwix helps our clients deliver unparalleled eСommerce experiences. We’re proud to work with the following companies: