Get Product Custom Option’s value programmatically in Magento 2.

Magento 2, Product with custom option used to allow customers to customize the product as per the need from a set of different Custom options.

The custom option is a native feature of Magento and you can add Custom option from Admin side in product Add/edit section.

If you want to get custom option’s value programmatically from Product, you need to use the below code in your module.

I did the code of custom option using Block file,

<?php
namespace Rbj\CustomOption\Block;

class CustomOption extends \Magento\Framework\View\Element\Template
{
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
        \Magento\Catalog\Model\ResourceModel\Product\Option\CollectionFactory $optionCollection,
        array $data = []
    ) {
        $this->productRepository = $productRepository;
        $this->optionCollection = $optionCollection;
        parent::__construct($context,$data);
    }

    public function getProductCustomOption($sku)
    {
        try {
            try {
                $product = $this->productRepository->get($sku);
            } catch (\Exception $exception) {
                throw new \Magento\Framework\Exception\NoSuchEntityException(__('Such product doesn\'t exist'));
            }
            $productOption = $this->optionCollection->create()->getProductOptions($product->getEntityId(),$product->getStoreId(),false);
            $optionData = [];
            foreach($productOption as $option) {
                $optionId = $option->getId();
                $optionValues = $product->getOptionById($optionId);
                if ($optionValues === null) {
                    throw \Magento\Framework\Exception\NoSuchEntityException::singleField('optionId', $optionId);
                }
                foreach($optionValues->getValues() as $values) {
                    $optionData[] = $values->getData();
                }
            }
            return $optionData;
        } catch (\Exception $exception) {
            throw new \Magento\Framework\Exception\NoSuchEntityException(__('Such product doesn\'t exist'));
        }
        return $product;
    }

}

In the Template file, You need to do as below,

$sku = "24-MB05";
$product = $block->getProductCustomOption($sku);
foreach ($product as $value) {
    echo $value['title'];echo "<br>"; //Option 1
    echo $value['price'];echo "<br>"; // 10.0000
    echo $value['sku'];echo "<br>"; //Option1_sku
    echo $value['sort_order'];echo "<br>"; // 1
}