how can i get the the attribute label from the attribute value in magento 2?
13,953
Solution 1
Please try this code
Step 1)First you have to load the products
$_productCollection = $block->getLoadedProductCollection();
Step 2)In the product listing page ,there will be a foreach loop for listing the products like this
foreach ($_productCollection as $_product)
Step3)Your code will be inside this loop.Place the below code at a place whereever you want to display the attribute label.
$_product->getResource()->getAttribute('your_attribute_code')->getFrontend()->getValue($_product);
Just replace your_attribute_code with whatever your attribute is named.
Solution 2
Try with
$_product->getAttributeText('farben');
Solution 3
Try this
<?php $_product = $block->getProduct(); ?>
<?php if (null !== $_product->getCustomAttribute('attribute_code')): ?>
<?= $_product->getAttributeText('attribute_code'); ?>
<?php endif; ?>
Author by
Divya Muralidharan
Works as Associate Software Engineer in PIT Solutions in Magento team.
Updated on June 04, 2022Comments
-
Divya Muralidharan almost 2 years
I got the attribute value 232 from the below code
$_product->getData('farben');
How I get its label from this value?
-
Hitesh Balpande over 5 years@Divya actually this code is used to get custom attribute values not label.If you have any idea please give related answer
-
Admin almost 5 yearsYou should maybe explain the code, so OP understands the problem.
-
Nuzil almost 2 years$_product->getResource() its a deprecated functionality and should not be used