1

I'm trying to get custom attribute value by using:

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

however I keep getting "No" as actual value, no matter which custom attribute I'm trying to get, it all returns "No", include both simple and configurable products.

I also tried to get the label and it returns the correct label: $_product->getResource()->getAttribute('attribute_code')->getFrontend()->getLabel()

What have I done wrong?

1

Hey please use below code :

$_product->getResource()->getAttribute('attribute_code')->setStoreId($currentStoreId)->getFrontend()->getValue($_product);

In above line i have just added ->setStoreId($currentStoreId) .

5
  • What's the best way of getting store id, I tried a few options, none of them works. This is one of them: blog.chapagain.com.np/…
    – Ethan Wan
    Oct 20 '16 at 10:11
  • Ok, I have correctly get my store id but it still doesn't work for me. The above code returns 'No'.
    – Ethan Wan
    Oct 20 '16 at 10:32
  • ok, so try below code $objectManager = Magento\Framework\App\ObjectManager::getInstance(); $_product = $objectManager->create('Magento\Catalog\Model\Product')->loa‌​d($product_id); $_product->getResource()->getAttribute('vendor')->setStoreId(0)->getFrontend()->getValue($_product);
    – Lucky
    Oct 21 '16 at 10:52
  • I get this error:
    – Ethan Wan
    Oct 24 '16 at 0:28
  • Error filtering template: Invalid method Magento\Catalog\Model\Product\Interceptor::loa‌​‌​d
    – Ethan Wan
    Oct 24 '16 at 0:28
0

I'm using color attribute here,

you can use below function in your block file:

/* $this->productModel is Magento\Catalog\Model\Product;*/

public function getColorValue($optionId){
    $colorValue = '';
    if($optionId) {
        $attribute = $this->productModel->getResource()->getAttribute('color');
        if ($attribute->usesSource()) {
            $colorValue = $attribute->getSource()->getOptionText($optionId);
        }
    }
    return $colorValue;
}

call the function as

$block->getColorValue($product->getColor())

you will get the color value.

0

Try to this Code to get attribute Value in Magento 2.

 $_getMyAttr = $_product->getResource()->getAttribute('my_attribute');

 // Get Value
 $attrTestValue = $_getMyAttr->getFrontend()->getValue($_product);
 // Get Label
 $attrTestLabel = $_getMyAttr->getStoreLabel();
0

Easy Solution here

-> Go to Store-> Attributes ->Product ->open your attribute and go to proprties. here just change attribute scope to "Global" and you will get your value in your code.

echo $product->getYourAttributeCode();

If this will fix your issue please mark as a solution.

Thank You

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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