Question

I want to get product attribute id from attribute Label

example: attribute label = Manufacturer

I want to get Manufacture attribute id from attribute Label

Any help would be appreciated.

Thanks.

Was it helpful?

Solution

Follow this below code to get attribute_id & attribute_code by using attribute label :

Construct Method :

protected $eavAttribute;

public function __construct(
    ....
    \Magento\Eav\Model\Attribute $eavAttribute,
    ....
){
    ....
    $this->eavAttribute = $eavAttribute;
    ....
}

public function yourFunction()
{
    $label = 'Manufacture';
    $attributeCollection = $this->eavAttribute->getCollection()->addFieldToFilter('frontend_label', ['eq' => $label])->getLastItem();
    echo $attributeCollection->getAttributeId(); // attribute ID
    echo $attributeCollection->getAttributeCode(); // attribute Code
}

Object Manager Method :

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$eavAttrObj = $objectManager->get('\Magento\Eav\Model\Attribute')->getCollection();
$attributeCollection = $eavAttrObj->addFieldToFilter('frontend_label', ['eq' => 'Created From'])->getLastItem();
echo $attributeCollection->getAttributeId();
echo $attributeCollection->getAttributeCode();

Use getLastItem() only if you have just a single record of that item. You can use backend_label instead of frontend_label if you want to perform in the backend side.

Note: I always recommended to use a construct method and avoid object manager.

Hope, It will helpful for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top