HummingbirdUK main logo

HummingbirdUK

Coding solutions to business problems

About us

We use code to create solutions to business challenges, bottle-necks and headaches.

If you think your business has a problem that can be solved through code, we are happy to chat things through without any obligation.

Get in touch

Bulk add attribute to attribute sets in Magento

Home / Blog / Bulk add attribute to attribute sets in Magento

Written by Giles Bennett

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] <?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(); } ?> [/php] There are only three lines which require amending : [php] ->setCodeFilter('ATTRIBUTE CODE') [/php] This is the code of the attribute you wish to add to the various attribute sets. [php] $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(); [/php] This is the attribute group name to which the attribute should be added. [php] ->setSortOrder(SORT ORDER) [/php] Naturally enough, this is the sort order of the attribute within the group - so how far down the list of attributes it appears.
Author : Giles Bennett

About the author

Giles Bennett built his first website in 1996, and is old enough to miss Netscape Navigator. Initially a lawyer, he jumped ship to IT in 2008, and after 5 years as a freelancer, he founded HummingbirdUK in 2013. He can be reached by email at giles@hummingbirduk.com.