Magento 2 Product Attributes – Getting Value from Product Attributes

attribute-setattributesmagento2productproduct-attribute

I have custom attributes for my products. Some attributes are in text format and some are in select list. I want to print those attributes in my template.
Here is code I am using:
`

$attributes = $_product->getAttributes();
$attrSetID = $_product->getAttributeSetId();
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();
$sql = "select attribute_group_id from eav_attribute_group where attribute_group_name = 'Additional Attributes'  AND attribute_set_id=$attrSetID";
$data = $connection->fetchAll($sql);
$groupId = array_pop($data);
if ($groupId && $attributes) {
    foreach ($attributes as $attribute) {
        if ($attribute->isInGroup($attrSetID, $groupId['attribute_group_id'])) {
            if ($attribute->getFrontend()->getValue($_product) == 'No') {
                $attrCode = $attribute->getAttributeCode();
//              $atest = $_product->getResource()->getAttribute($attrCode)->getFrontend()->getValue($_product);
//              $options = $attribute->getSource()->getAllOptions();
            } else {
                echo  $attribute->getFrontendLabel() . ' : ' . $attribute->getFrontend()->getValue($_product) . '<br />';
            }
        }
    }                            
}

And my problem is that Magento print only attributes which are not select type. For attributes that are select type Magento print "No".

I tried to print selected value of attribute like this, but output is still "No".

  1. $_product->getResource()->getAttribute($attrCode)->getFrontend()->getValue($_product);
  2. $_product->getAttributeText('custom_attribute_code')

In google I found only couple solutions for Magento 1x, so if someone can help me, i would appreciate it.
Thank you.

Best Answer

Please make sure that you have assigned "your attribute" to appropriate Attribute Set.

Also, select your attribute for the product as well.

You can get attribute text by using below code.

echo $_product->getAttributeText('your attribute');

if $_product doesn't work for you then try below code to get product data.

$_product = $this->getProduct();

OR

$_product = $block->getProduct();

Hope it works and help you.

Related Topic