How to add new custom category attribute in Magento

Sometimes you need to extend functionality of Magento categories. There is several ways to do that, I will show you how it can be done.
You can do that by modifying and adding data into some of tables directly, but it can be waste of time if you don’t know what you are doing.
This post will describe how you can add new custom category attribute in your Magento store via sql_setup script.

MySQL setup script will look something like this, it depends on your needs and how you would like to configure your new attribute:

$installer = $this;
$installer->startSetup();
 
$entityTypeId     = $installer->getEntityTypeId('catalog_category');
$attributeSetId   = $installer->getDefaultAttributeSetId($entityTypeId);
$attributeGroupId = $installer->getDefaultAttributeGroupId($entityTypeId, $attributeSetId);
 
$installer->addAttribute('catalog_category', 'new_cat_attrb',  array(
    'type'     => 'int',
    'label'    => 'New Category Attribute',
    'input'    => 'text',
    'global'   => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
    'visible'           => true,
    'required'          => false,
    'user_defined'      => false,
    'default'           => 0
));
 
 
$installer->addAttributeToGroup(
    $entityTypeId,
    $attributeSetId,
    $attributeGroupId,
    'new_cat_attrb',
    '11'					//last Magento's attribute position in General tab is 10
);
 
$attributeId = $installer->getAttributeId($entityTypeId, 'new_cat_attrb');
 
$installer->run("
INSERT INTO `{$installer->getTable('catalog_category_entity_int')}`
(`entity_type_id`, `attribute_id`, `entity_id`, `value`)
    SELECT '{$entityTypeId}', '{$attributeId}', `entity_id`, '1'
        FROM `{$installer->getTable('catalog_category_entity')}`;
");
 
 
//this will set data of your custom attribute for root category
Mage::getModel('catalog/category')
    ->load(1)
    ->setImportedCatId(0)
    ->setInitialSetupFlag(true)
    ->save();
 
//this will set data of your custom attribute for default category
Mage::getModel('catalog/category')
    ->load(2)
    ->setImportedCatId(0)
    ->setInitialSetupFlag(true)
    ->save();
 
$installer->endSetup();

In your config.xml file of your module you will need to add this part in order to install correctly your new category attribute:

<resources>
	<new_attribute_csv_setup>
	  <setup>
		<module>New_Attribute</module>
		<class>Mage_Catalog_Model_Resource_Eav_Mysql4_Setup</class>
	  </setup>
	  <connection>
		<use>core_setup</use>
	  </connection>
	</new_attribute_setup>
	<new_attribute_setup_write>
	  <connection>
		<use>core_write</use>
	  </connection>
	</new_attribute_setup_write>
	<new_attribute_setup_read>
	  <connection>
		<use>core_read</use>
	  </connection>
	</new_attribute_setup_read>
</resources>

Pay attention on class tag here, class must be: “Mage_Catalog_Model_Resource_Eav_Mysql4_Setup”.

If you did this correctly, you will get something like this:

Enjoy coding!

You made it all the way down here so you must have enjoyed this post! You may also like:

Adding gallery tab to a CMS page Antun Martinovic
, | 5

Adding gallery tab to a CMS page

How I learned to stop worrying and love 3rd party modules for Magento Luka Rajcevic
Luka Rajcevic, | 2

How I learned to stop worrying and love 3rd party modules for Magento

Solving problems with Category tree database information Nikola Stojiljkovic
Nikola Stojiljkovic, | 19

Solving problems with Category tree database information

83 comments

  1. I tested with Magento 1.6.1.0 . I think it work with version 1.6.2 .

    You just do as I note, it’ll work well

  2. This looks like a nice and decent technique.

    Does it also work with magento community 1.6.2?

    I am trying to imlement it but there is nothing being saved into the database nor is there anything in the category config page in admin.

  3. Ok Haney, for that you need to review the class fie “Mage_Adminhtml_Block_Catalog_Category_Tab_Design” and the _prepareLayout() function in the same. From this file you can get the idea to how to add the tab in the Catalog –> Category management.

  4. Thanks Senthil. But don’t want to assign products to multiple categories instead would like to assign categories to other categories.
    I’ll talk about a real time scenario. Say I have 3 categories: Men, Women and Hoods. In Men category, there are shirts, hats and hoods and the same for Women category. But when you click on Hoods, it should show all the hoods from Men and Women categories.

  5. I’m looking for to add a new tabpage under category in magento admin, which loads the category grid. Idea is to associate multiple categories to one category and on the front end, when you click on that particular category, it should show products from all the associated categories. Is there any better solution then create a new tabpage with categories grid?
    If not then can anybody help me to guide how to create a new tabpage under category in admin…

  6. @senthil thank you for reply.

    Admin–> Catalog->Categories has just one record – root derictory (id = 2). But DB table catalog_category_entity has two records:

    entity_id | 1 | 2 |
    entity_type_id | 3 | 3 |
    attribute_set_id | 0 | 3 |
    parent_id | 0 | 1 |

    path | 1 | 1/2 |

    And another question – what setter setImportedCatId should do?

  7. Hi Anthony,

    You can find the “Category Id” in Admin–> Catalog->Categories [For Community].
    Admin–> Catalog->Categories->Manage Categories [For Enterprise].

  8. Thx for the nice article. Colud you describe one point pls. You wrote Mage::getModel(‘catalog/category’)->load(1)… and Mage::getModel(‘catalog/category’)->load(2). 1 & 2 – it is some IDs. But which table it has?

  9. Your post has helped me figure out something in my custom module for which I was wrecking my brains since days. I am trying to add an extra field to review_detail table for which my module is overriding Review Model files. But the data is not getting saved to the table because there is no Setup.php in Review/Model files in core. Any pointers on this one?

  10. I am trying to get this to work in Magento 1.6.1 with no joy. I have tried just about every variation I am seeing on this page and the only thing that I can see even being kind of an issue is that all of the tables in 1.6 have “mage_” as a prefix. Any thoughts on this would be greatly appreciated.
    -Thanks

  11. Hi Karthick ,

    Go to Manage Products–>Click select All present in the grid and in the right top corner of the listing grid you can see “Actions” from there select “Update Attributres” it will take to a page which have three tabs in the left panel from there click inventory there you can see stock option. Please set Qty greater than Zero and update. Thats All. Also you can manage the stock for each product by Edit and click on inventory you have the same option. The Error cause for not listing the product is may be the “Out of stock”. And also some other cause may due to not map the products with the Active category . Please check that too.

    All the best.

  12. Hi i’m using magento 1.6.0… Modern theme… i was able to add the product category in the dashboard but not getting it in home page… what i do…? im new to Magento will you help me?

  13. I found the problem:
    I forgot settings the ‘backend’ => ‘eav/entity_attribute_backend_array’
    and I changed ‘user_defined’ => true

  14. I have added a multiselect attribute for categories as Bozo suggested. The attribute display normally in categories, but it is not saved when I save the category.

    Here is the attribute I added:
    $installer->addAttribute(‘catalog_category’, ‘display_item’, array(

    ‘label’ => ‘Item to display’,

    ‘type’ => ‘varchar’,

    ‘input’ => ‘multiselect’,

    ‘default’ => ”,

    ‘class’ => ”,

    ‘backend’ => ”,

    ‘frontend’ => ”,

    ‘source’ => ‘xcategory/Valuelist’,

    ‘global’ => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,

    ‘visible’ => true,

    ‘required’ => false,

    ‘user_defined’ => false,

    ‘searchable’ => false,

    ‘filterable’ => false,

    ‘comparable’ => false,

    ‘visible_on_front’ => false,

    ‘visible_in_advanced_search’ => false,

    ‘unique’ => false

    ));

    Please help me to save the attribute when I save the categories. Thanks a lot.

  15. Hi, I have one really good query, can you guys tell me how to add one new field in front end property.
    Someone just ask me if I can add one new field in his front end property which will remain as text field.?

  16. previous one is misleading . Please review this

    <?xml version="1.0"?>
    <config>
    <modules>
            <Companyname_Yourmodulename>
                <version>0.1.0</version>
            </Companyname_Yourmodulename>
        </modules>
        <frontend>
          	<routers>
    			<yourmodulename>
    				<use>standard</use>
    				<args>
    					<module>Companyname_Yourmodulename</module>
                        <frontName>yourmodulename</frontName>
    				</args>
    			</yourmodulename>
    		</routers>
        </frontend>
    <global>
    		<resources>
    			<yourmodulename_setup>
    			  <setup>
    			    <module>Companyname_Yourmodulename</module>
    			    <class>Mage_Catalog_Model_Resource_Eav_Mysql4_Setup</class>
    			  </setup>
    			  <connection>
    			    <use>core_setup</use>
    			  </connection>
    			</yourmodulename_setup>
    		</resources>
    	</global>
    </config>
  17. I have found the problem and i have used this

    <?xml version="1.0"?>
    <config>
    <global>
    		<resources>
    			<yourmodulename_setup>
    			  <setup>
    			    <module>Companynamwe_Yourmodulename</module>
    			    <class>Mage_Catalog_Model_Resource_Eav_Mysql4_Setup</class>
    			  </setup>
    			  <connection>
    			    <use>core_setup</use>
    			  </connection>
    			</yourmodulename_setup>
    		</resources>
    	</global>
    </config>
  18. I have found the problem and i have used this

    Companynamwe_Yourmodulename
    Mage_Catalog_Model_Resource_Eav_Mysql4_Setup

    core_setup

  19. Thanks. This Post saved me a lot of headaches.

    Can you tell how much time you’ve spent to write this snippet? Especially with importing products it’s sometimes a staggering amount of time I spent to get it running :-/

  20. i found it… i forgot to adapt this little piece of code:

    $installer->run("
    INSERT INTO `{$installer->getTable('catalog_category_entity_int')}`
    (`entity_type_id`, `attribute_id`, `entity_id`, `value`)
        SELECT '{$entityTypeId}', '{$attributeId}', `entity_id`, '1'
            FROM `{$installer->getTable('catalog_category_entity')}`;
    ");

    it should be

    $installer->run("
    INSERT INTO `{$installer->getTable('catalog_category_entity_varchar')}`
    (`entity_type_id`, `attribute_id`, `entity_id`, `value`)
        SELECT '{$entityTypeId}', '{$attributeId}', `entity_id`, '1'
            FROM `{$installer->getTable('catalog_category_entity')}`;
    ");

    to play with varchar attributes…

    thanks again, guys!

  21. hi,

    thanks a LOT for the hints! with your help I managed to set up a multiselect attribute for additional static blocks to be attached to categories!

    BUT:

    it appears the data is not saved correctly. while catalog_category_entity_varchar table receives the correct values, all I get in catalog_category_flat_store_1 table is the value ‘1’, no matter what I enter.

    here’s the code I used for the multiselect attribute:

    $installer->addAttribute('catalog_category', 'cat_blocks', array(
    'label' => 'Blocks',
    'type' => 'varchar',
    'input' => 'multiselect',
    'default' => '',
    'class' => '',
    'backend' => 'eav/entity_attribute_backend_array',
    'frontend' => '',
    'source' => 'hme_xtracms/entity_attribute_source_blocks',
    'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
    'visible' => true,
    'required' => false,
    'user_defined' => false,
    'searchable' => false,
    'filterable' => false,
    'comparable' => false,
    'visible_on_front' => false,
    'visible_in_advanced_search' => false,
    'unique' => false
    ));

    the source model brings up the correct values. any idea what I might be missing?

    thanks a lot for your help!

  22. I am newbie to Magento development

    I have created a new module for this on app/code/local/company/catalog. In this I have added 2 directory for ./etc/config.xml and ./sql/catalog_setup/mysql4-install-1.0.0.php. I have also added a file to app/etc/modules/company_catalog.xml but it still does not seem to work. Can someone please help.
    Wasted almost 2 days on doing this instead of directly changing the database.

  23. @myself:
    I needed to add the New_Attribute.xml in etc/modules. After refreshing the cache the new attribute was added 😀

  24. Thanks for this script. I’ve created my own to add an attribute to a category. Now my question is, how do i execute this or does Magento do this by itself?
    At the moment I don’t see the new attribute 🙁

  25. how to update the custom attribute value programatically to some default value on creation or updation of the category.

  26. Actually, Tony, just figured out that if you re-index your store (specifically the Category Flat Data table), you’ll end up with your EAV fields in the category info. You may have to disable/re-enable the Flat Catalog Categories flag first (that’s when mine started working).

    Sweet!

  27. Tony, it’s probably because you have Flat Catalog Category (in System -> Config -> Catalog) set to Yes. Just ran into that myself.

    Anyone have any suggestions on how to best add fields to Flat Catalog Categories? Or do we need to alter the structure of the flat table in the db?

  28. Hi,

    I have your code implemented on a 1.5.0.1 store, the attribute appears in the admin and saves fine. However when I come to access the attribute it does not work. I have the following code…

    $category = Mage::getModel('catalog/category')->load($catId);
    $category->getData('custom_attribute')

    I can see by using the following code that my model does not contain the attribute..

    $category = Mage::getModel('catalog/category')->load($catId);
    print_r($category->debug());

    Any ideas why that might happen?

    Thank!!

  29. @Vedran,
    This is very simple tip Thanks. Can u please tell me how can I add an attribute in “Display setting” tab. I have to change the GROUPID or ATTRIBUTESET_ID?

  30. @Newbie
    not necessarily..you can create “update” sql_setup script of existing module and just increse the nuber of module version.

    @Byron
    It’s developed and tested on 1.5.0.1
    I don’t believe that there is too much difference between those 2 version so it should work. Try again.

  31. Thanks Vedran for the write up. For some reason, I am unable to get this to work properly on v1.5. I followed your instructions to the letter (including fixed a typo / should be ). Not sure what I missed.

  32. Nice post. To be honest I’ve never needed to use much more than Category title, description and image, however this is a pretty clever script.

    Love the simplicity of it too.

  33. Thanks Vedran. Probably makes sense to use some sort of prefix to reference the site to make it unique.

  34. Very nice work Vedran. Do these sort of changes cause any problems when it is time to update Magento?

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.

Tell us about your project

Drop us a line. We'd love to know more about your project.