Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies

Thursday, October 13, 2022

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:

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;
}

Execute the above code and get attribute & attribute options programmatically in Magento 2.

Hope we have been helpful to get it done.

No comments:

Post a Comment