Mass import magento 2 categories script

This tutorial explains how to mass import magento 2 categories programmatically. Please click to download the sample CSV file. The import script create the categories in the magento admin as shown below.

Import magento 2 categories programmatically

Please also refer the tutorials that explains clearly how to import magento 2 and magento version 1 categories programmatically. The script create the categories as shown below.

/**
 * Import categories to Magento
 *
 * @param $arrResult
 */
function importCategories( $arrResult, $objectManager, $storeId )
{

    $parentId = '2';
    $list = array();

    foreach ( $arrResult as $import_category ) {
        
        try {
            
            $enabled = ( strtolower( $import_category[16] ) == 'true' ) ? 1 : 0;
            $parentId = ( $import_category[1] == 0 )? '2' : $list[$import_category[1]];            
            
            $url = strtolower($import_category[2]);
            $cleanurl = trim(preg_replace('/ +/', '', preg_replace('/[^A-Za-z0-9 ]/', '', urldecode(html_entity_decode(strip_tags($url))))));
            $categoryFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory');
            /// Add a new sub category under root category
            $category = $categoryFactory->create();
            $category->setName(ucfirst($import_category[2]));
            $category->setIsActive( $enabled );
            $category->setUrlKey($cleanurl);
            $category->setData('description', strip_tags($import_category[11]));
            $category->setMetaTitle(trim($import_category[5]));
            $category->setMetaDescription(trim(strip_tags($import_category[6])));
            $category->setMetaKeyword(trim($import_category[7]));
            $category->setParentId($parentId);
            $mediaAttribute = array ('image', 'small_image', 'thumbnail');
            $category->setImage( $import_category[6], $mediaAttribute, true, false);// Path pub/meida/catalog/category/
            $category->setStoreId($storeId);
            $rootCat = $objectManager->get('Magento\Catalog\Model\Category')->load($parentId);
            $category->setPath($rootCat->getPath());
            $category->save();
            $list[$import_category[0]] = $category->getId();
            echo 'Category ' . $category->getName() . ' ' . $category->getId() . ' imported successfully' . PHP_EOL;
        } 
        catch (Exception $e) 
        {
            echo 'Something failed for category ' . $import_category[2] . PHP_EOL;
            print_r($e);
        }
    }
    return $list;

}

Share this Tutorial