There are various ways of retrieving a Magento category attribute, however depending on how it’s stored in the database you can’t always rely on the same method each time.
Let’s say for example that you want to get the meta_description value for a category in the category view template, this field is a native attribute that exist as a column in the catalog_category_flat_store_1 table, so calling one of the following methods would work fine:
1 2 3 4 5 6 7 | // Get the meta_description value using a magic getter echo $_category->getMetaDescription(); // Get the meta_description value using the getData method echo $_category->getData('meta_description'); |
But what if you want to get the value of a custom category attribute? Well, the above methods simply won’t work, as custom attributes are usually stored in the eav_attribute table.
The following custom function will retrieve the value of any Magento native category attribute or custom category attribute, just add it the appropriate block or helper class of your module:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | /** * @desc Get the value of any category attribute * @param int | object $category The category id or a Mage_Catalog_Model_Category instance * @param string $code The attribute code * @return string | int | bool | array The attribute value or array if multiselect */ public function getCategoryAttributeValue($category, $code) { $categoryId = $category; if ($category instanceof Mage_Catalog_Model_Category) $categoryId = $category->getId(); $storeId = Mage::app()->getStore()->getId(); $resourceModel = Mage::getResourceModel('catalog/category'); $attribute = $resourceModel->getAttributeRawValue($categoryId, $code, $storeId); $frontendInput = $resourceModel->getAttribute($code)->getData('frontend_input'); if ($frontendInput == 'multiselect') return explode(',', $attribute); return $attribute; } |
The function will except either a category model or category id along with the attribute code and return the attribute value. If the attribute is stored as a multiselect field, the values will be returned as an array instead.
Example template usage
1 2 3 | <?php echo $this->helper('customhelper')->getCategoryAttributeValue($_category, 'my_custom_attribute');?> |