Home » Magento2 December 2009

Magento: How to get attribute name and value?

Attribute in Magento is like a property. All Products, Categories, Orders, Customers, etc. have attributes. For example, the attribute of a product is its name, sku, description, image, etc.

This article will show you how to get attribute name and value for any product.

Get attribute’s name, value, type, and other parameters

The attribute code in the case below is my_attribute.

/**
 * get attribute collection
 */
$attribute = $_product->getResource()->getAttribute('my_attribute');
/**
 * get attribute type
 */
$attribute->getAttributeType();
/**
 * get attribute Label
 */
$attribute->getFrontendLabel();
/**
 * get attribute default value
 */
$attribute->getDefaultValue();
/**
 * check if the attribute is visible
 */
$attribute->getIsVisible();
/**
 * check if the attribute is required
 */
$attribute->getIsRequired();
/**
 * get attribute value
 */
$attributeValue = Mage::getModel('catalog/product')->load($_product->getId())->getMyAttribute();

Get value from a select box attribute

The attribute code is supposed to be ‘my_attribute

$attributeValue = Mage::getModel('catalog/product')
			->load($_product->getId())
			->getAttributeText('my_attribute');

Load any particular attribute by attribute code

$attributeInfo = Mage::getResourceModel('eav/entity_attribute_collection')
				->setCodeFilter(YOUR_ATTRIBUTE_CODE)
				->getFirstItem();

// echo "<pre>"; print_r($attributeInfo->getData()); echo "</pre>"; 

Get all option value list for the particular attribute

You can see above that I got attribute information by attribute code. My attribute information is stored as $attributeInfo. See code above.

Here is the code to get all option values for my attribute $attributeInfo.

$attributeOptions = $attributeInfo->getSource()->getAllOptions(false);
// echo "<pre>"; print_r($attributeOptions); echo "</pre>";

Get all options of any attribute

Getting all options of attribute with attribute-code “color“.

$attribute = Mage::getSingleton('eav/config')->getAttribute('catalog_product', 'color');
if ($attribute->usesSource()) {
	$options = $attribute->getSource()->getAllOptions(false);
}

Get attribute’s option information by option id

I have my attribute as $attributeInfo.
I have my attribute’s option value array as $attributeOptions.
See code above.

Suppose, I want to get detail information of any option listed in strong>$attributeOptions array. Here is the code to do so:-

$attributeId = $attributeInfo->getAttributeId();
$optionId = YOUR_ATTRIBUTE_OPTION_ID;

$attributeOptionSingle = Mage::getResourceModel('eav/entity_attribute_option_collection')   
				->setPositionOrder('asc')
				->setAttributeFilter($attributeId)
				->setIdFilter($optionId)
				->setStoreFilter()
				->load()
				->getFirstItem();
									
// echo "<pre>"; print_r($attributeOptionSingle); echo "</pre>";

Get attribute of particular entity type

Here, I am going to get information about ‘order_id‘ attribute of ‘invoice‘ entity type.

$entityType = Mage::getModel('eav/config')->getEntityType('invoice');
$entityTypeId = $entityType->getEntityTypeId();
		
$attribute = Mage::getResourceModel('eav/entity_attribute_collection')
				->setCodeFilter('order_id')
				->setEntityTypeFilter($entityTypeId)
				->getFirstItem();				

Get attribute options of Configurable product

$confAttributes = $_product->getTypeInstance(true)->getConfigurableAttributesAsArray($_product);

Hope this helps. Thanks.

From Mukesh Chapagain's Blog, post Magento: How to get attribute name and value?

php magento mukesh chapagain

Get New Post by Email

Find me on

Facebook Twitter Google+ LinkedIn RSS Feed
  • http://www.shockmaker.com Riccardo

    I have a multilanguage Magento website.

    I’m using “$attribute->getFrontendLabel();”
    to retrieve the label of a attribute,
    but it returns always the default label set in the field “Admin”.

    Is it possible to retrieve the label of the current selected language of the site instead of the default one?

  • http://blog.chapagain.com.np Mukesh

    Yeah.. there seem to be some problem in Magento attribute for multilanguage website.

    Try this: echo $this->__($attribute->getFrontendLabel());

    If it doesn’t work then here is another solution.

    $attributeLabel = $attribute->getFrontendLabel();
    $translationArray = Mage::app()->getTranslator()->getResource()->getTranslationArray();
    echo $translationArray["Mage_Catalog::".$attributeLabel];

  • jatinder

    hey can u please guide me how to access the attribute if Input Type is choosen yes/no and how to access its value that’s Yes/No…so i want to set condition according to it on view.phtml page under product..
    can u please guide me through this…….

  • Anupama

    Hi,

    Thanks.
    This helps me to get attribute value.
    Also want to add one more thing here,

    If your attribute has select box, for example I have attribute “Metal” :

    Gold
    Silver
    Platinum

    By applying the following code :
    $attributeValue = Mage::getModel('catalog/product')
    ->load($_product->getId())
    ->getMetalType();

    this will output the “6″ as a selected value id for the attribute.

    $attributeValue = Mage::getModel('catalog/product')
    ->load($_product->getId())
    ->getAttributeText('metal_type');

    This will output “Gold”, the exact selected value.

    Thanks again for this Attribute code explanation!

  • http://blog.chapagain.com.np Mukesh

    Thank You Anupama !

  • http://smartosc.com Paolo

    hi,
    i just cant’ call getAttribute,
    the site hung a while and returned a blank page
    i dont know what really happened
    help me guys….. :(

  • Eric

    Is there any way to get attributes name and value by attributes code not belong to any products. My mean get attributes not product attributes.

  • http://blog.chapagain.com.np Mukesh

    @Eric:

    Here is the code to get attribute detail and attribute values by attribute code:-


    $attributeName = YOUR_ATTRIBUTE_CODE;
    $product = Mage::getModel('catalog/product');

    $collection = Mage::getResourceModel('eav/entity_attribute_collection')
    ->setEntityTypeFilter($product->getResource()->getTypeId())
    ->addFieldToFilter('attribute_code', $attributeName);

    $attribute = $collection->getFirstItem()->setEntity($product->getResource());

    // print_r($attribute->getData());

    $attributeOptions = $attribute->getSource()->getAllOptions(false);

    // print_r($attributeOptions);

    Hope this helps.

    Source: http://stackoverflow.com/questions/1332742/magento-retrieve-products-with-a-specific-attribute-value

  • NAGENDRAN

    hi

    how to get configurable products attributes values and options. pls help it is urgent

  • codep

    very elegant examples…

    I’ve put code to get attribute value into product’s issalabe method (mage – catalog – model – product.php) and sometimes it returns attribute value but sometimes it doesn’t – i.e. when product->isSaleable() is called from list.phtml attribute value does not exist, but when is called from simple.phtml it returns attribute value normaly. Do you have any idea why is that?

  • http://magentoexp.blogspot.com ansh

    @codep use this to get attribute value for any product

    $attributeValue = Mage::getModel('catalog/product')
    ->load($product->getId())
    ->getAttributeText($attrb_code);

  • jarus

    Hello , how can we delete attribute value without going to have to go to the attribute itself , is there a way to delete attribute value like we access attribute values?

  • http://www.bluehorse.in Md.Shawkat Alam

    i have the attribute manufacturer.

    i have a option of that attribute acer.

    i want to know the id of that option.

    i have to echo in magento admin panel.

    help me

  • nate

    any help to set attributes when creating a product. I am able to pull up the attribute set and reference the option values in the array but I cant seem to set a attribute value when creating a product. This code creates a product but its color and size options are not set.

    $product = Mage::getModel(‘catalog/product’);
    $product->setTypeId(‘simple’);
    $product->setTaxClassId(0); //none
    $product->setWebsiteIds(array(1)); // store id
    $product->setAttributeSetId(705); //Product Attribute Set
    $product->setSku(ereg_replace(“\n”,”",”1111″));
    $product->setName(ereg_replace(“\n”,”",”PRODUCT NAME”));
    $product->setDescription(“product description”);
    $product->setInDepth(“product description product description”);
    $product->setPrice(“29.95″);
    $product->setShortDescription(ereg_replace(“\n”,”",”product desc”));
    $product->setWeight(0);
    $product->setStatus(1); //enabled
    $product->setVisibility(1); //nowhere
    $product->setMetaDescription(ereg_replace(“\n”,”",”product description meta desc”));
    $product->setMetaTitle(ereg_replace(“\n”,”",”product description meta title”));
    $product->setMetaKeywords(“product description meta keywords”);
    $product->save();

    try{
    $product->save();
    $productId = $product->getId();
    echo $product->getId() . “, $price, $itemNum added\n”;
    }
    catch (Exception $e){
    echo “$price, $itemNum not added\n”;
    echo “exception:$e”;
    }

  • biblop

    Little piece of code to get all the values for selected attribute’s options :

    $_product->getResource()->getAttribute(‘my_multiselect_attribute_name’)->getFrontend()->getValue($_product);

    Return all values coma separated.

  • http://blog.chapagain.com.np/ Mukesh

    $confAttributes = $_product->getTypeInstance(true)->getConfigurableAttributesAsArray($_product);

  • Michael Lee Baker

    Nice Post!! Bar far the most clear and understand on how to do this easily.

  • adrian

    Hi there Mukesh, do you know of a way to remove an attribute’s options by code? For instance if I have the attribute color and I wish to remove the option ‘red’.

    Thanks in advance!

  • http://www.facebook.com/people/Albert-Bezuhov/100000478125473 Альберт Безухов

    Thanks so much! Your advice has helped me many times since I started working with Magento engine

  • Chris

    How do you get only attributes that have been assigned to a product?

  • Ezhhhhh

    Thanx a lot for sharing (^___^)

  • Gary

    Thanks bro, this magento could drive any developer out of his mind…

  • Savlajigar

    Hi Mukesh,
    Is their any way to delete all options of an attribute?
    Regards,
    JIgar

  • Savlajigar

    Hi Mukesh,
    Is their any way to delete all options of an attribute?
    Regards,
    JIgar

  • Konrad

    Hi Mukesh,
    How can I change value of option?

  • Manimaran Kalimuthu

    Yes Me Tooooooooooo

  • Mshperling770

    you are the champion,man!

  • Manish Chauhan

    Thank You……:)
    it works for me.

  • Choussamaster

    for who need to show the attribute label in the cart page ‘default.phtml” file
    change  htmlEscape($_option['label']) ?> by

      setCodeFilter($_option['label'])->getFirstItem()->getFrontend_label();?>            htmlEscape($attributeLabel) ?> :

  • Choussamaster

    for who need to show the attribute label in the cart page ‘default.phtml” file
    change  htmlEscape($_option['label']) ?> by

      setCodeFilter($_option['label'])->getFirstItem()->getFrontend_label();?>            htmlEscape($attributeLabel) ?> :

  • Pingback: вывод атрибута - CodusWiki

  • Sourav Mondal

    foreach(Mage::getModel(‘catalog/product’)->getCollection()->getData() as $product)
    {

    echo Mage::getModel(‘catalog/product’)->load($product['entity_id'])->getName();

    }
     

  • Ivn

    Hi there,

    I would like to display all customer attribute labels (name,email,telephone,) in a drop down box.
    Something Like Attributes – (dropdown list – Name,Telephone,Email,Created At,Customer Group, Company, ZipCode, country, Satte/Province, etc..)

    How to do that. Please reply as soon as possible. this is very much needed for me to use in an application
     

  • Ivn

    Hi there,

    Is there any way I could display all customer attribute labels (name,email,telephone,) in a drop down list and then as per the value selected retrieve that particular attribute’s id, label, default value, etc ?

  • Alex Secutec

    Thank you so much, that is very usefull, but I have a question:
     Mage::getModel(‘catalog/product’)->load($_product->getId())->getAttributeText(‘icontags’);
     allows us to display Attributes values but could you give me a tips if I want display the “id” of each  values of the attribute.

  • http://www.facebook.com/oschmid Oliver Schmid

    Hi, thanks a lot for sharing your knowledge!

    I need to get the data of the field “admin” of a Dropdown Attribute. How can I get that?

  • Nilesh

    thanks for the code chunk, helped a lot..

  • mukesh

    Thanks a lot ……………………….

  • Pingback: magento: lấy tên và giá trị attribute của sản phẩm « tandatbr.wordpress.com

  • Victor D.

    Hello, I, instead, I need to export all attributes and attribute set in csv, you have an idea how can I do?

  • Carlos Cárdenas

    Thanks a lot, this saved me a lot of time. But I have one question.
    Is it possible to disable one value of one attribute in code? So, if I have 3 possible values for the attribute for one product, the user can only choose between the other two values, this based on certain logic Thanks :)

  • Pingback: [Magento] How to get attribute name and value? « 9collective

  • Praful

    I used “Get attribute’s option information by option id” section

    but its throwing error as “Integrity constraint violation: 1052 Column ‘option_id’ in where clause is ambiguous”

    pls help me in that. I am using magento 1.7.0.0

  • cyril

    +1

  • saravanan P

    hey,can you please help
    i need to list out attributes in the category page not for all. only category related attributes. Please help me to resolve it asap. Thanks in advance

  • Aliasse

    One of the best article about Magento attributes ! So useful ! Thanks :)