Magento2 Product Attribute – Get Select Option ID and Label for Configurable Product

magento2product-attribute

How to get an option value based on the option id in Magento, or get an option id based on the option code ?

Example: how to get the color attribute option id 10 from the label "Red", and get the value "Red" if the option id is 10 ?

Best Answer

you can do it same as magento 1,

More information in details, Visit, Get Option id and Label from configurable product

//get option label based on option id from product object

$optionId = 10;

$attr = $_product->getResource()->getAttribute('color');
 if ($attr->usesSource()) {
       $optionText = $attr->getSource()->getOptionText($optionId);
 }
//get option text ex. Red

//get option id based on option label

$attr = $_product->getResource()->getAttribute('color');
 if ($attr->usesSource()) {
       $option_id = $attr->getSource()->getOptionId("Red");
 }

//get option id ex. 10
Related Topic