Question

I'm wondering if there's a right way to get the value of a product attribute, in a generic way.

EDIT: Or whatever I can use to get the info from a dropdown or text field using the same mechanism

I know I can do: $product->getData('attribute_code')

But if the code it's a dropdown select then I'll be getting a value which doesn't represent really what the users selected. For example in a dropdown to select a t-shirt size options would be (s,l,xl) and internal values (1,2,3)

It's a way to know how to get the attribute type to later identify what I should be looking for or the right way to pick the value.

Was it helpful?

Solution

for dropdown use this code

<?php echo $attr = $_product->getResource()->getAttribute('your_attribute_code')->getFrontend()->getValue($_product); // dropdown attribute"?>

the other code only displays the ID from the database tabel when used for dropdown. this is why you get 1,2,3

OTHER TIPS

Actually magento internally use magic method so if your attribute code is tshirt_size then magic method would be getTshirtSize()

if you want to get a text of tshirt_size attribute then you can use the below method which is return selected size (i.e. l)

$product->getAttributeText('tshirt_size');

if you want that value of tshirt_size then you can use the below method.

$product->getTshirtSize();
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top