Magento – How to get selected custom options

custom-options

I have the following code. The drawback of the code is it is getting all custom options for a product while I want to get only those options which are selected by the customer on the product page.

$items = $order->getAllItems();
foreach ($items as $item) {
    $product = Mage::getModel('catalog/product');
    $prodSku = $item->getSku();
    $productId = $product->getIdBySku($prodSku);

    $product->load($productId);
    $product = $item->getProduct();
    $productId = $item->getItemId();
    $options = $product->getOptions();
    foreach($options as $_option) {
        echo $_option->getTitle();    
    }
}

Best Answer

You can try to replicate the way Magento shows the options in the order view page.
Here goes:

$items = $order->getAllItems();
//or you can use $order->getAllVisibleItems();
//create an instance of the item renderer block.
$block = Mage::app()->getLayout()->createBlock('sales/order_item_renderer_default');
foreach ($items as $item) {
    //attach the item to the block
    $block->setItem($item);
    //get the options 
    $_options = $block->getItemOptions();
    foreach ($_options as $option) {
        $label = $option['label'];
        $textValue = $option['print_value'];
        //do something with $label and $textValue
    }
}