Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies

Sunday, June 30, 2013

Magento: How to get all attribute codes by product object or attribute set ID

Today, I’m writing an script for exporting Magento products to an XML file. In my PHP script, I have decided to create an class for holding the data of Magento product. In that class which defines all attributes from a product like the editing product screen from back-end
But I see there are many attributes from this screen so it will be hard for us to define all attribute manually. I have found the way to get all attribute code from an attribute set ID of product.
Here is the code snippet you can also use:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function getAttributeCodes($product)
{
        // get attribute set ID from product
        $setId = $product->getAttributeSetId();
        $groups = Mage::getModel('eav/entity_attribute_group')
            ->getResourceCollection()
            ->setAttributeSetFilter($setId)
            ->setSortOrder()
            ->load();
             
        /* @var $node Mage_Eav_Model_Entity_Attribute_Group */
        $attributeCodes = array();
        foreach ($groups as $group) {
            $groupName          = $group->getAttributeGroupName();
            $groupId            = $group->getAttributeGroupId();
 
            $attributes = Mage::getResourceModel('catalog/product_attribute_collection')
                ->setAttributeGroupFilter($group->getId())
                ->addVisibleFilter()
                ->checkConfigurableProducts()
                ->load();
            if ($attributes->getSize() > 0) {
                foreach ($attributes->getItems() as $attribute) {
                    /* @var $child Mage_Eav_Model_Entity_Attribute */
                    $attributeCodes[] = $attribute->getAttributeCode();
                }
            }
        }
 
        return $attributeCodes;
}

No comments:

Post a Comment