Quantcast
Channel: Magento Development – Coding Basics
Viewing all articles
Browse latest Browse all 21

Get Magento Attribute Name and Value

$
0
0

All products in Magento have attributes assigned to them. The default attributes consist of but are not limited to the sku, price, description, url key and so forth. You can also create custom attributes yourself to add extra information to a product. If you want to get the attribute name and value of your Magento product you can use the code below.

The attribute code used in the code below is custom_attribute.

/**
 * get attribute collection
 */
$attribute = $_product->getResource()->getAttribute('custom_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();

If you want to get the value of a select box attribute you can use the following code. Again, the attribute code used below is custom_attribute.

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

If you want to load any particular attribute by attribute code use this:

$attributeInfo = Mage::getResourceModel('eav/entity_attribute_collection')
				->setCodeFilter(YOUR_ATTRIBUTE_CODE)
				->getFirstItem();
 
// echo "<pre>"; print_r($attributeInfo->getData());

As you can see above, we’ve gotten all the information for our particular attribute. The information is stored in $attributeInfo. Get all the options listed for this particular attribute:

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

To get all the options for an attribute you can use the following code. The attribute code used here is size.

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

If you want to get the attribute options of a specific configurable product in Magento use this:

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

If you have any other code that could be useful to readers of this page, please submit them in the comment section below and I will include them in the article.

The post Get Magento Attribute Name and Value appeared first on Coding Basics.


Viewing all articles
Browse latest Browse all 21

Trending Articles