HummingbirdUK main logo

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 Magento attribute to attribute sets

Home / Blog / Bulk add Magento attribute to attribute sets

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?

Answer...yes - quickly and easily using the following script.

<?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.

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.