I have an array of attribute codes which I need to get the values of:
$attributes = array(
'Category' => 'type',
'Manufacturer' => 'brand',
'Title' => 'meta_title',
'Description' => 'description',
'Product Link' => 'url_path',
'Price' => 'price',
'Product-image link' => 'image',
'SKU' => 'sku',
'Stock' => 'qty',
'Condition' => 'condition',
'Shipping cost' => 'delivery_cost');
After iterating through a product collection I get the frontend values of the attributes like so:
$attributeId = Mage::getResourceModel('eav/entity_attribute')
->getIdByCode('catalog_product', $attribute_code);
$attribute = Mage::getModel('catalog/resource_eav_attribute')
->load($attributeId);
$value = $attribute->getFrontend()->getValue($product);
Simply using $product->getDate($attribute)
won't work with dropdowns and multi-selects, it just returns their id and not their frontend value.
While the code above works, it seems to be a long way around getting the value, but more importantly it runs quite slow. Is there a faster/more sensible way to get the frontend values for product attributes?
Edit
I now have the following (after dealing with special cases like image
and qty
) which is a bit easier on the eyes and does seem to run quicker (although I don't know why):
$inputType = $product->getResource()
->getAttribute($attribute_code)
->getFrontend()
->getInputType();
switch ($inputType) {
case 'multiselect':
case 'select':
case 'dropdown':
$value = $product->getAttributeText($attribute_code);
if (is_array($value)) {
$value = implode(', ', $value);
}
break;
default:
$value = $product->getData($attribute_code);
break;
}
$attributesRow[] = $value;
If anyone can improve this (make it simpler/more efficient), please post an answer.
For dropdowns and multiselects and only with products (this isn't a general EAV trick) you can use getAttributeText()
.
$value = $product->getAttributeText($attribute_code);