How to get product attribute option label by id and get attribute option id by label in Magento 2

In this blog, we will learn how to get product attribute option label by option id and get option id by option label.

when you have used a configurable type product then you may face situations to get product attribute option label by option id and get option id by option label. Once you get an attribute value from product $_product->getColor() then it returns option ID.

Let’s create a helper class and look at how to get option labels by option id and get option id by option label.

<?php

namespace Mageclues\ProductAttribute\Helper;

use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Catalog\Model\ProductFactory;

class Data extends AbstractHelper
{
protected $_productFactory;

    public function __construct(
        Context $context,
        ProductFactory $productFactory
    ) {
        $this->_productFactory = $productFactory;
        parent::__construct($context);
    }

    // To get Option Label by Option id
    public function getOptionLabelByOptionId($attributeCode, $optionId)
    {
        $product = $this->_productFactory->create();
        $isAttributeExist = $product->getResource()->getAttribute($attributeCode);
        $optionText = '';
        if ($isAttributeExist && $isAttributeExist->usesSource()) {
            $optionText = $isAttributeExist->getSource()->getOptionText($optionId);
        }
        return $optionText;
    }

   // To get Option Id by Option Label
    public function getOptionIdByOptionLabel($attributeCode,$optionLabel)
    {
        $product = $this->_productFactory->create();
        $isAttributeExist = $product->getResource()->getAttribute($attributeCode);
        $optionId = '';
        if ($isAttributeExist && $isAttributeExist->usesSource()) {
            $optionId = $isAttributeExist->getSource()->getOptionId($optionLabel);
        }
        return $optionId;
    }
}

You can call the helper function in a .phtml file or anywhere you want to display.

$attributeHelper = $this->helper('Mageclues\ProductAttribute\Helper\Data');
$optionValue = $attributeHelper->getOptionLabelByOptionId('color','50');
// Here, color is attribute code and  10 is id of option
// Result is Orange

$optionId = $attributeHelper->getOptionIdByOptionLabel('color','Orange'); // result is 50
// Here, 'color' is attribute code and  'Orange' is label of option
// Result is 10

We hope this blog is useful for you. Please leave a comment if you have any questions.

Thank you!

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *