Bulk add attribute to attribute sets in Magento

The other day a client added a new attribute, but then wanted to add it to all their attribute sets – all 190 of them. Could this be done programmatically, they asked?

Bulk Add Attribute To Attribute Sets


Answer…yes – quickly and easily using the following script (download it from the end)

<?php
require_once 'app/Mage.php';
umask(0);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$attSet = Mage::getModel('eav/entity_type')->getCollection()->addFieldToFilter('entity_type_code','catalog_product')->getFirstItem();
$attSetCollection = Mage::getModel('eav/entity_type')->load($attSet->getId())->getAttributeSetCollection(); 
$attributeInfo = Mage::getResourceModel('eav/entity_attribute_collection')
        ->setCodeFilter('ATTRIBUTE CODE')
        ->getFirstItem();
$attCode = $attributeInfo->getAttributeCode();
$attId = $attributeInfo->getId();
foreach ($attSetCollection as $a) {
	$set = Mage::getModel('eav/entity_attribute_set')->load($a->getId());
        $setId = $set->getId();
        $group = Mage::getModel('eav/entity_attribute_group')->getCollection()->addFieldToFilter('attribute_set_id',$setId)->addFieldToFilter('attribute_group_name', 'ATTRIBUTE GROUP NAME')->setOrder('attribute_group_id',ASC)->getFirstItem();
        $groupId = $group->getId();
        $newItem = Mage::getModel('eav/entity_attribute');
        $newItem->setEntityTypeId($attSet->getId())
                  ->setAttributeSetId($setId)
                  ->setAttributeGroupId($groupId)
                  ->setAttributeId($attId) 
                  ->setSortOrder(SORT ORDER) 
                  ->save();
    }

?>

There are only three lines which require amending :

->setCodeFilter('ATTRIBUTE CODE')

This is the code of the attribute you wish to add to the various attribute sets.

$group = Mage::getModel('eav/entity_attribute_group')->getCollection()->addFieldToFilter('attribute_set_id',$setId)->addFieldToFilter('attribute_group_name', 'ATTRIBUTE GROUP NAME')->setOrder('attribute_group_id',ASC)->getFirstItem();

This is the attribute group name to which the attribute should be added.

->setSortOrder(SORT ORDER) 

Naturally enough, this is the sort order of the attribute within the group – so how far down the list of attributes it appears.

Want to talk to us about your project?