Magento – Get Custom Option Values of a product magento 2

attribute-optionscustom-optionsmagento2product-attributesimple-product

I have two custom options for a product. Color and Size and both are drop-downs. In product detail pages, I have to display all available colors of that product.

I tried the following code and it works:

$_product = $block->getProduct();
foreach ($_product->getOptions() as $o) {
    foreach ($o->getValues() as $value) {
        print_r($value->getData());
    }
}

But it returns all the values of Color and Size. But I only need the color values. That is I want to select the custom options by color.

Best Answer

Try this:

$_product = $block->getProduct();
foreach ($_product->getOptions() as $o) {
    if ($o->getTitle() != 'Color') { // or another title of option
        continue;
    }
    foreach ($o->getValues() as $value) {
        print_r($value->getData());
    }
}

You should search for your option by the title because the option ID is unknown.