Magento create categories on import

I have created this code, during my training period. I remember I had spent around 2-3 days to run this code successfully!

What does it do?

If you are importing products in your Magento store through normal import process,This code is very useful.

Categories will be created dynamically,while products are being imported. Also hierarchy will be maintained, I mean child-parent relationship can be made.

Steps

 

  1. Copy Product.php file from core/Mage/ImportExport/Model/Import/Entity to local/Mage/ImportExport/Model/Import/Entity.
  2. Now open that file, and add below functions.
    public function _checkcategory(array $rowData, $rowNum)
    {
    	$rootId= Mage::app()->getStore(1)->getRootCategoryId();
    	$collection = Mage::getModel('catalog/category')->getCollection()->addAttributeToSelect('name');
    	foreach ($collection as $cat)
    	{
    		$name[]=$cat->getName();
    	}
    	$getcategory[$rowNum]=explode("|",$rowData['category_ids']);
    	$countsub=count($getcategory[$rowNum]);
    	$comp=in_array($getcategory[$rowNum][0],$name);
    	if (!$comp)
    	{
    		$category = Mage::getModel('catalog/category');
    		$category->setName($getcategory[$rowNum][0])
    		// ->setUrlKey($urlKey)
    		->setIsActive(1)
    		->setDisplayMode('PRODUCTS')
    		->setIsAnchor(1)
    		->setDescription('This is category')
    		->setAttributeSetId($category->getDefaultAttributeSetId());
    		$parentCategory = Mage::getModel('catalog/category')->load($rootId);
    		$category->setPath($parentCategory->getPath());
    		$category->save();
    		//break;
    	}
    	if($countsub>1)
    	{
    		for($i=1;$i<$countsub;$i++)
    		{
    		$compsub=in_array($getcategory[$rowNum][$i],$name);
    		if(!$compsub)
    		{
    			$subcategory = Mage::getModel('catalog/category');
    			$subcategory->setName($getcategory[$rowNum][$i])
    			->setIsActive(1)
    			->setDisplayMode('PRODUCTS')
    			->setIsAnchor(1)
    			->setDescription('This is category')
    			->setAttributeSetId($subcategory->getDefaultAttributeSetId());
    			$j=$i-1;
    			$newparentCategory = Mage::getModel('catalog/category')
    			->getCollection()
    			->addFieldToFilter('name', array('eq'=>$getcategory[$rowNum][$j]));
    			foreach ($newparentCategory as $subcat)
    			{
    				$sub=$subcat->getId();
    				$path=$subcat->getPath();
    			}
    			$subcategory->setPath($path);
    			$subcategory->save();
    		}
    		}
    	}
    }
    
    public function _categoryId(array $rowData, $rowNum)
    {
    	$categoryname[$rowNum]=explode("|",$rowData['category_ids']);
    	for($i=0;$i<count($categoryname[$rowNum]);$i++)
    	{
    		$getcollection = Mage::getModel('catalog/category')->getCollection()
    		->addFieldToFilter('name', array('eq'=>$categoryname[$rowNum][$i]));
    		foreach ($getcollection as $getcat)
    		{
    			$this->getid[]=$getcat->getId();
    		}
    	}
    return $this->getid;
    }
    
    public function _saveCategories(array $rowData,$rowNum,array $getid)
    {
    	static $tableName = null;
    	if (!$tableName) {
    	$tableName = Mage::getModel('mage_importexport/import_proxy_product_resource')->getProductCategoryTable();
    	}
    	$getid=$this->getid;
    	if ($getid)
    	{
    		$categoriesIn = array();
    		$delProductId = array();
    		foreach ($getid as $cid)
    		{
    			$product_sku = $rowData[self::COL_SKU];
    			$productId = Mage::getModel("catalog/product")->getIdBySku( $product_sku );
    			$delProductId[] = $productId;
    			$categoriesIn[] = array('product_id' => $productId, 'category_id' => $getid, 'position' => 1);
    		}
    		if (mage_importexport_Model_Import::BEHAVIOR_APPEND != $this->getBehavior())
    		{
    			$this->_connection->delete(
    			$tableName,
    			$this->_connection->quoteInto('product_id IN (?)', $delProductId)
    			);
    		}
    		if ($categoriesIn)
    		{
    			$this->_connection->insertOnDuplicate($tableName, $categoriesIn, array('position'));
    		}
    	}
    return $this;
    }
    
  3. After adding this functions, you can have to call them, add following lines in that file.
    $this->_checkcategory($rowData, $rowNum);
    $this->_categoryId($rowData, $rowNum);
    $this->_saveCategories($rowData, $rowNum,$getid);
    
  4. Save this file.
  5. In csv file categories should be in form like this : Cat1 | Cat2 | Cat3

Now run the import process,and categories (Cat1 > Cat2 > Cat3) will be created.

Any issues? Let me know in comments.

The following two tabs change content below.
Ankur Dholakia

Ankur Dholakia

Magento Developer | Entrepreneur at iBiz Technologies
Magento Developer, Entrepreneur, Day Dreamer!
WhatsAppShare

There are no comments

Leave a Reply

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

Start typing and press Enter to search

Shopping Cart