Pages

Wednesday, November 5, 2014

How to get Magento's attribute names and values

For my own reference, quick and dirty:
$product = Mage::getModel('catalog/product')->load($productId);
$attribute_value = $product->getData($attribute_code);

The attribute code used below is 'attribute_code'.

/**
 * get attribute collection
 */
$attribute = $_product->getResource()->getAttribute('attribute_code');

/**
 * 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())->getAttributeCode();

//or without loading the product
$attributeValue = Mage::getResourceModel('catalog/product')->getAttributeRawValue($productId, 'attribute_code', $storeId);

/**
* get attribute option code/value list 
*/
$attribute = Mage::getSingleton('eav/config')->getAttribute('catalog_product', 'attribute_code');
$options = $attribute->getSource()->getAllOptions(false);


in a view.php or similar, you can access the attribute text related to a product like:
<?php echo $_product->getAttributeText('attribute_code'); ?>

No comments:

Post a Comment