Magento 2 get product attribute option value

Today we will talk about how to get product attribute option value programmatically in Magento 2. This programming tutorial explains in detail, how to get a product attribute option value and attribute option id. By following this example you can get the attribute option data like value and id. So let’s start with our example.

protected $_attributeLoading;
   
       public function __construct(
            .....
              \Magento\Catalog\Model\ResourceModel\ProductFactory   $attributeLoading,  
              ....
                                    ) {
                parent::__construct($context);
           
                ....
                $this->_attributeLoading = $attributeLoading;
                ....
   
        }
     
   
       public function getAttributeOptionId($attribute,$label)
        {
            $poductReource=$this->_attributeLoading->create();
            $attr = $poductReource->getAttribute($attribute);
             if ($attr->usesSource()) {
                    return  $option_id = $attr->getSource()->getOptionId($label);
             }
        }
       public function getAttributeOptionText($attribute,$label)
        {
            $poductReource=$this->_attributeLoading->create();
            $attr = $poductReource->getAttribute($attribute);
             if ($attr->usesSource()) {
                    return  $option_Text = $attr->getSource()->getOptionText($label);
             }
        }
      $this->getAttributeOptionId('color','//optionLabel');
      $this->getAttributeOptionText('color','//optionId');

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!