Create Magento categories tree programmatically

Data entry in Magento is a quite time consuming operation. Especially if you have a lot of environments and want to keep them all up to date. In this article we’ll create Magento categories tree programmatically with ability to update them without re-installing database.

First add a mysql upgrade script in your custom module:

Then form an array with your categories and sub-categories. Pay attention – Top Category Two has a child with a same name and slug as Top Category One:

Next let’s write a function which will create/update the categories:

This function automatically pick up all children categories and run itself to create them recursively. At the beginning of the function we check if desired category already exists in scope of current parent category. If it does – update category with new values, if not – create a new one.

Hint: if you need to make a slight changes in your category tree – just delete a row (or lower the version) in core_resource table to run script again.

And last but not least add logic to walk through the categories array:

Make sure you set current store to Mage_Core_Model_App::ADMIN_STORE_ID and update mode to false to avoid any errors. Then retrieve root category data and setup new categories under root. And finally return Magento to current store and set update mode back to finish upgrade.

For your convenience here is the full upgrade file listing:

If you have any specific settings for each category – move it from saveCategory() function to categories array. For example: And then:
Make sure to refresh cache and reindex Catalog URL Rewrites after this upgrade.

This is it folks, hope that help. If you find this article helpful (or vice versa) – don’t hesitate to rate it below and share to help others in their Magento journey.

If you have any suggestions – please leave a comment.


Create Magento categories tree programmatically
4.7 (93.33%) 6 vote[s]

What do you think?

Required fields are marked *