In Magento 2 the attributes define the product's features like product size and product color.
Some product attributes are by default into the system like product description, product price and product name.
In this article, we will discuss How we can Get Attribute & Attribute Options Programmatically in Magento 2.
So with the help of this code, we can get the attribute and their options easily and quickly.
To Programmatically get Attribute and their options in Magento 2 follow the below code.
If sometimes you need to get the attribute & attribute options to set somewhere, you can get the values by custom coding it.
<?php namespace Mageants\Blog\Helper; use Magento\Catalog\Model\ResourceModel\Eav\Attribute; use Magento\Catalog\Model\Product\Attribute\Repository; class Data extends \Magento\Framework\App\Helper\AbstractHelper { /** * @var attribute */ protected $attribute; /** * @var attributeRepository */ protected $attributeRepository; /** * @param Attribute $attribute * @param Repository $attributeRepository */ public function __construct( Attribute $attribute, Repository $attributeRepository ) { $this->attribute = $attribute; $this->attributeRepository = $attributeRepository; } // getAttribute public function getAttributeCodeById($id) { $attributeModel = $this->attribute->load($id); $attributeCode = $attributeModel->getAttributeCode(); return $attributeCode; } // getAttributeOption public function getAttributeOptionByCode($code) { $options = $this->attributeRepository->get($code)->getOptions(); return $options; } } |
By using this helper object, we can easily get attribute code and attribute option like below.
<?php public function __construct( ......... \Mageants\Blog\Helper\Data $helper, ......... ) { ...... $this->helper = $helper; ...... } $id = 141; $attributecode = $this->helper->getAttributeCodeById($id); echo "attributecode". '='. $attributecode; $attributeoption = $this->helper->getAttributeOptionByCode($attributecode); foreach($attributeoption as $options_value) { print_r($options_value->getData()); } |
Using the above code we get attribute code of 141 attribute id.
Conclusion:
Using above article, you can easily understand How to Get Magento 2 Attribute & Attribute Options Programmatically.
If you have any query regarding above code implementation then you can contact us or let us know in comment section.