Get Product Attribute Information From Attribute Code in Magento 2
All the products in Magento 2 have some attributes like description, SKU, brand etc. While developing an e-commerce website many times we need to display the product attribute information on product listing page or product detail page.
In this code snippet, we will see how to fetch product attribute name, value, type and other required information from attribute code.
Note: For the demonstrated purpose we have used Objectmanager.Codextblog never recommend the direct use of ObjectManager.One should always use a constructor method to instant an object.
Get Attribute Information
<?php //attribute code $attributeCode = 'color'; //entity type $entityType = 'catalog_product'; $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $attribute = $objectManager->get(\Magento\Eav\Model\Entity\Attribute::class) ->loadByCode($entityType, $attributeCode); //attribute id echo $attribute->getAttributeId(); //Name/Title of attribute echo $attribute->getFrontendLabel(); //attribute default value echo $attribute->getDefaultValue(); //get backend type echo $attribute->getBackendType(); //get input type echo $attribute->getFrontendInput(); ?>
Get All Options of Select Attribute
//attribute code $attributeCode = 'material'; //entity type $entityType = 'catalog_product'; $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $attribute = $objectManager->get(\Magento\Eav\Model\Entity\Attribute::class) ->loadByCode($entityType, $attributeCode); $attributeId = $attribute->getAttributeId(); $attributeOption = $objectManager->get(\Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection::class) ->setPositionOrder('asc') ->setAttributeFilter($attributeId) ->setStoreFilter() ->load(); foreach ($attributeOption as $option){ echo $option->getValue()."<br>"; }
Hope this code snippet helps you. If you liked this post, then please like us on Facebook and follow us on Twitter.
Leave a Comment
(0 Comments)
Useful Magento 2 Articles
Author Info
Chirag
Connect With Me