How to Get Magento 2 Attribute & Attribute Options Programmatically
For Magento 2, attributes are options to describe the products and its features. It is a property of the product. It helps potential customers to choose the best-fit product for their needs. By default, Magento 2 products have predefined attributes like name, price, description etc. To show the characteristics of a product, custom options are created in the store. The value of attributes is called attribute options.
Default Magento does not allow to get Magento 2 attribute & attribute options. If sometimes you need to get the attribute & attribute options to set somewhere, you can get the values by custom coding it. Today, I have come up with a custom code to get Magento 2 attribute & attribute options programmatically!
Method to get Magento 2 attribute & attribute options programmatically:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
use Magento\Catalog\Model\ResourceModel\Eav\Attribute; use Magento\Catalog\Model\Product\Attribute\Repository; protected $attribute; protected $attributeRepository; public function __construct( Attribute $attribute, Repository $attributeRepository) { $this->attribute = $attribute; $this->attributeRepository = $attributeRepository; } public function getAttributeOption($attributeId) { $attributeModel = $this->attribute->load($attributeId); $attributeCode = $attributeModel->getAttributeCode(); $options = $this->attributeRepository->get($attributeCode)->getOptions(); return $options; } |
Hope we have been helpful to get it done.
If you find any difficulty in the execution of the code or stuck somewhere, do let me know by commenting below.
I’ll be happy to help!
Found the article good enough?
Don’t forget to flash 5 stars 🙂
Jignesh Parmar
An expert in his field, Jignesh is the team leader at Meetanshi and a certified Magento developer. His passion for Magento has inspired others in the team too. Apart from work, he is a cricket lover.
Prev
Magento 2 SEO Guide: Tips, Tricks, and Best Practices
How to Use Registry in Magento 2
Next