By In Magento

Create product attribute programmatically

Create product attribute is common operation in Magento, it can be successfully done from Magento back-end without any issues. In case that you already have loaded store with lot of attribute sets and products it can be really time consuming to add attribute to every attribute sets. If there are only few attributes sets that can be done manually, however if there are 10 or even more attribute sets operation could last quite a bit.

I found a small workaround in form of simple PHP script that can be used easily to create product attribute and assign it to all attribute sets (or only to attribute sets that you want).

Create a PHP file, we will name it ‘install-attribute.php’ and copy code from bellow into it (don’t forget PHP start/end tags):

require_once 'app/Mage.php';

// Attribute basic data
$attributeName = ‘Product Custon Attribute’; // Name of the attribute
$attributeCode = ‘product_custom_attribute’; // Code of the attribute
$attributeGroup = ‘Custom Group’; // Group to add the attribute to
// Attribute configuration data
$data = array(
‘type’ => ‘varchar’, // Attribute type
‘input’ => ‘text’, // Input type
‘global’ => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL, // Attribute scope
‘required’ => false, // Is this attribute required?
‘user_defined’ => false,
‘searchable’ => false,
‘filterable’ => false,
‘comparable’ => false,
‘visible_on_front’ => false,
‘unique’ => false,
‘used_in_product_listing’ => true,
// Adding basic data
‘label’ => $attributeName

// Installer code to create attribute with new installer class (can be used in non-EAV setup)
$installer = Mage::getResourceModel(‘catalog/setup’, ‘catalog_setup’);
$installer->addAttribute(‘catalog_product’, $attributeCode, $data);

// Notice: Default Attribute Set have ID 4

// Add the attribute to the all attribute proper sets and proper groups:
$entity = Mage_Catalog_Model_Product::ENTITY;
$attributeSetIds = $installer->getAllAttributeSetIds($entity);
foreach($attributeSetIds as $attributeSetId)
$installer->addAttributeToGroup(‘catalog_product’, $attributeSetId, $attributeGroup, $attributeCode);


Comments in code explain every section clearly, so we will run through it quickly:
– first part we define all attribute parameters
– second part is installer action
– finally in third part we assign attribute to attribute sets

This is just a example and code should be modified according to your needs, also it is important to create a proper backup of data base before running script. In general nothing bad could happen but it might happen that you are not satisfied with created attribute and sometimes it is easier to restore backup than to erase attribute.

Leave a Reply

Your email address will not be published. Required fields are marked *