Simple example on how to programatically create two level categories in Magento

Recently I have been working on a new site that has large number of products and not so little number of categories. As you all know, Magento import system is somewhat obscure, does not seem to allow you a lot in terms of modifications. You are bound to creating a proper CSV file in order to do a valid import. One of the difficulties with such system often comes down to “how do I transfer all my categories” or “how to I transfer all my images” from old shop system to Magento. My so far practice has simple answer on that: Sometimes, there just isn’t any simply solution. Sometimes you will waste hours of coding just to build a proper CSV file that will later be passed to the import system.

This shop I was working on was relatively “flat” in its architecture. Flat in terms that it had just a few tables, with not so great “normalization”. However, this “flat” architecture produced a lightning fast web shop with speed of page loading that Magento can most of the time dream of, unless placed on truly quality server.

So, how do we transfer the categories from old shop system to the Magento. We all know that Magento CSV file requires category id’s to be placed in the appropriate CSV column. That means we need to have our categories created in front. Here is a simple example on how to programatically create two level categories in Magento.

public function createCategories()
{
	//The root category in Magento, the one you get by default install, usually has the id 2
	$_rootParentCat = 2; 
 
	/* START Create first level categories */
	$_rootCats = $this->_db->fetchCol("SELECT DISTINCT ProductCategory1 FROM SomeProductCategoryTable");
 
 
	foreach($_rootCats as $_rootCat)
	{
		$_c = $this->_db->fetchOne("SELECT ProductCategory1URL FROM SomeProductCategoryTable WHERE ProductCategory1 = ?", array($_rootCat));
 
 
		if($_c != '' && $_c != 'na')
		{
			$_cat = new Mage_Catalog_Model_Category();
			$_cat->setName($_rootCat);
			$_cat->setUrlKey($_c);
			$_cat->setIsActive(1);
 
			$parentCategory = Mage::getModel('catalog/category')->load($_rootParentCat);
			$_cat->setPath($parentCategory->getPath());				
 
			$_cat->save();
			Zend_Debug::dump($_c);
 
			/* START Create second level categories */	
			$_childCats = $this->_db->fetchCol("SELECT DISTINCT ProductCategory2 FROM SomeProductCategoryTable WHERE ProductCategory1 = ?", array($_rootCat));
 
			foreach($_childCats as $_childCat) 
			{
				$_cc = $this->_db->fetchOne("SELECT ProductCategory2URL FROM SomeProductCategoryTable WHERE ProductCategory2 = ?", array($_childCat));
 
				if($_cc != '' && $_cc != 'na')
				{
					$_catChild = new Mage_Catalog_Model_Category();
					$_catChild->setName($_childCat);
					$_catChild->setUrlKey($_cc);
					$_catChild->setIsActive(1);	
 
					$parentCategory = Mage::getModel('catalog/category')->load($_cat->getId());
					$_catChild->setPath($parentCategory->getPath());							
 
					$_catChild->save();	
					Zend_Debug::dump($_cc);	
					unset($_catChild);						
				}
			}
			/* END Create second level categories */
			unset($_cat);		
		}
 
	}
	/* END Create first level categories */
 
 
	/** Zend_Debug::dump($c->debug());
		array(25) {
		  ["entity_id"] => string(1) "3"
		  ["entity_type_id"] => string(1) "3"
		  ["attribute_set_id"] => string(1) "3"
		  ["parent_id"] => string(1) "2"
		  ["created_at"] => string(19) "2010-05-24 12:14:56"
		  ["updated_at"] => string(19) "2010-05-24 17:02:17"
		  ["path"] => string(5) "1/2/3"
		  ["position"] => string(1) "1"
		  ["level"] => string(1) "2"
		  ["children_count"] => string(1) "0"
		  ["name"] => string(6) "Sample"
		  ["url_key"] => string(6) "sample"
		  ["meta_title"] => string(0) ""
		  ["display_mode"] => string(8) "PRODUCTS"
		  ["custom_design"] => string(0) ""
		  ["page_layout"] => string(0) ""
		  ["url_path"] => string(6) "sample"
		  ["is_active"] => string(1) "1"
		  ["is_anchor"] => string(1) "0"
		  ["custom_design_apply"] => string(1) "1"
		  ["description"] => string(21) "Sample category here."
		  ["meta_keywords"] => string(0) ""
		  ["meta_description"] => string(38) "Meta Sample category description here."
		  ["custom_layout_update"] => string(0) ""
		  ["available_sort_by"] => string(0) ""
		}
	 */
}

Please not that the example above is not generally applicable. You will notice that I used it to programatically create only the two level category system. Thus, the example is not to be used as simply “copy-paste”.

Depending on the size (number) of the categories in the old shop, programatically in place of manually creating categories can save you great deal of time.

Hope that above example helps to some of you (to certain extent).


6 comments

  1. Here is the source code for creating multiple category

    $category = Mage::getModel(‘catalog/category’);
    $category->setName($cat);
    $category->setUrlKey(‘new-category’);
    $category->setIsActive(1);
    $category->setDisplayMode(‘PRODUCTS’);
    $category->setIsAnchor(1); //for active achor
    $category->setStoreId(Mage::app()->getStore()->getId());
    $parentCategory = Mage::getModel(‘catalog/category’)->load($id);
    $category->setPath($parentCategory->getPath());
    $category->save();
    $pId=$category->getId();
    $categories = Mage::getResourceModel(‘catalog/category_collection’);

  2. How to set image for category via code.

    I tried image will insert in database table but not set in thumb image.

    When I am upload from back end It Will work fine.

    Please give me solution as soon as possible.

  3. How to implement active category in 3rd level.
    viz.
    1
    1.1
    1.1.1
    1.1.2
    1.1.3
    1.1.4
    1.2
    1.3
    1.4
    2
    3

    when i click 1.1

  4. Hi, I was used code like and set the category customLayoutUpdate , layoutUpdate is updated , but problem is not working we again save the category manually.

    If you know the problem , can you plz reply the solution.

    I was used like ,
    $category = new Mage_Catalog_Model_Category();
    $category->setName(‘Financing’);
    $category->setUrlKey(‘financing’);
    $category->setIsActive(1);
    $category->setDisplayMode(‘PAGE’);

    $category->setCustomLayoutUpdate(‘
    ‘);
    $category->setIsAnchor(1);
    $category->setPath(‘1/3’);

    $category->save();
    unset($category);

    thanks,

  5. Hi,
    thanks for sharing your interesting code!
    I’ve “upgraded” it to be used for three levels and use of different queries.
    Now i need to execute the metod but i can’t find any example… can you suggest me how?

    Thanks in advance,
    Nicola

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