Magento 2.x – How to get product option value on an order item by option sku.
Hi there, hope your doing well and staying safe at home.
In this post, i’ll show you how to get a custom option value, iterating through order items, with the option sku.
First step, is having your option sku, that should be configured on the catalog product edit page, of your admin panel, like this:
Afterwards, the following snippet will help you, you will only need to pass as a parameter, the order id where the product has been purchased:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
protected $_orderRepository; protected $_options; public function __construct( ... \Magento\Sales\Api\OrderRepositoryInterface $orderRepository, \Magento\Catalog\Model\Product\Option $options ) { .... $this->_orderRepository = $orderRepository; $this->_options = $options; ... } public function getMyCustomOptionValue($orderId) { $order = $this->_orderRepository->get($orderId); foreach ($order->getAllVisibleItems() as $orderItem) { $customOptions = $this->_options->getProductOptionCollection($orderItem->getProduct()); if (empty($customOptions)) { return ''; } foreach ($customOptions as $option) { if ($option->getData('sku') == 'my-custom-option-name') { $optionId = $option->getData('option_id'); if (!empty($optionId)) { $options = $orderItem->getProductOptions(); if (!empty($options['info_buyRequest'])) { if (!empty($options['info_buyRequest']['options'][$optionId])) { return $options['info_buyRequest']['options'][$optionId]; } } } } } } return ''; } |
Hope it helps you.
Happy coding.!