1

How to get a simple product Customizable option value and key in a .phtml file using product id or Sku Magento 2 ?

2 Answers 2

2

Here is the following code snippet to get custom product option by loading product Id :

 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

//Load product by product id
        $productObject = $objectManager->create('Magento\Catalog\Model\ProductFactory')
                ->create()->load($product_id)->getOptions();
        foreach ($productObject as $o) {
            foreach ($o->getValues() as $value) {
                $value->getData();
            } 
        }

By this code you will get custom option in phtml .

2
/** @var CheckoutSession */
protected $checkoutSession;

/**
 * @param CheckoutSession $checkoutSession
 */
public function __construct(Magento\Checkout\Model\Session $checkoutSession) {
    $this->checkoutSession = $checkoutSession;
}

public function execute() {

    /** @var \Magento\Quote\Model\Quote  */
    $quote = $this->checkoutSession->getQuote(); //here you will get quote data
    $quote = $block->getCheckoutSession()->getQuote();
    $items = $quote->getAllItems(); 
    foreach($items as $item) {
      echo 'ID: '.$item->getProductId().'<br />';
      echo 'Name: '.$item->getName().'<br />';
      echo 'Sku: '.$item->getSku().'<br />';
      echo 'Quantity: '.$item->getQty().'<br />';
      echo 'Price: '.$item->getPrice().'<br />';

      $productOptions = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct());
      if (isset($productOptions['options'])) {
        foreach ($productOptions['options'] as $key => $value) {
            $optionType = $value['option_type'];
            echo 'optionType: '.$optionType.'<br />';
        }
     }

      echo "<br />";            
    }
}
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.