8

I got the attribute value 232 from the below code

    $_product->getData('farben');

How I get its label from this value?

0

3 Answers 3

25

Please try this code

  1. First you have to load the products

    $_productCollection = $block->getLoadedProductCollection();

  2. In the product listing page ,there will be a foreach loop for listing the products like this

    foreach ($_productCollection as $_product)

  3. Your code will be inside this loop.Place the below code at a place where ever you want to display the attribute label.

$_product->getResource()->getAttribute('your_attribute_code')->getFrontend()->getValue($_product);

4
  • It works for me. Commented Oct 18, 2016 at 12:36
  • 4
    getResource is deprecated in Magento 2.3.0
    – PathToLife
    Commented Jan 8, 2019 at 8:01
  • 1
    @DivyaMuralidharan this code return attributes value not label Commented Jan 11, 2019 at 14:24
  • is there an optimized way to get the option label, instead of using the for loop with bulk products?
    – Haritha
    Commented Jun 10, 2021 at 7:37
14
 $_product = $productObject; //get product object

 $optionId = 232;   
 $attr = $_product->getResource()->getAttribute('attribute_code');
 if ($attr->usesSource()) {
    $optionText = $attr->getSource()->getOptionText($optionId);
 }
 echo $optionText;
3
  • how can we get custom attribute label in custom module block using phtml file,actually i am able to get custom attribute value. Commented Jan 11, 2019 at 13:43
  • 1
    This run faster than accepted answer
    – Nolwennig
    Commented Apr 14, 2019 at 23:39
  • Perfect solution! Commented Apr 23, 2020 at 11:27
-6

$product = $this->objectFactory->get('Magento\Catalog\Model\Product')->load($product_id);

$attributes = $product->getAttributes();

foreach ($attributes as $attribute) {
     label => __($attribute->getStoreLabel()),
     'value' => $value, //attribute Value
     'code' => $attribute->getAttributeCode(), //attribute Code
}

1
  • 12
    How is this accepted? It has errors and incorrect syntax.
    – Tisch
    Commented May 11, 2017 at 16:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.