Magento 2

How to Get Order Item Selected Options in Magento 2?

Magento 2

How to Get Order Item Selected Options in Magento 2?

Today, we'll explore how to retrieve the selected options of order items in Magento 2. This feature is especially useful when you want to display custom options or attributes chosen by customers during the checkout process.

To get the selected options of an order item, you need to load the order and loop through its items. For each item, you can access the selected options using the getProductOptions() method.

Here's an example code snippet on how to achieve this:

use Magento\Sales\Api\Data\OrderItemInterface;

// Load the order by increment ID or order ID
$orderId = YOUR_ORDER_ID_OR_INCREMENT_ID;
$order = $this->_objectManager->create(\Magento\Sales\Model\Order::class)->loadByIncrementId($orderId);

// Get all items of the order
$items = $order->getAllItems();

// Loop through each order item to get selected options
foreach ($items as $item) {
    $productOptions = $item->getProductOptions();
    
    // Check if the item has options
    if (isset($productOptions[OrderItemInterface::PRODUCT_OPTIONS_KEY])) {
        $selectedOptions = $productOptions[OrderItemInterface::PRODUCT_OPTIONS_KEY];
        // Process and display the selected options as needed
        // For example:
        foreach ($selectedOptions as $option) {
            $optionTitle = $option['label'];
            $optionValue = $option['value'];
            // Do something with the option data (e.g., echo it)
            echo "$optionTitle: $optionValue <br>";
        }
    }
}

You can add the above code snippet to a custom module, a Magento controller, or a template file to display the selected options on the frontend or perform other actions based on the selected options.

Please Note: It's essential to follow Magento's best practices and avoid direct use of the object manager (\Magento\Framework\ObjectManagerInterface) in a production environment. Instead, use dependency injection to obtain the order object in your custom module or controller.

Happy coding, and enjoy working with Magento 2!