Import magento 2 categories programmatically

This tutorial explains how to import magento 2 categories programmatically. The script read category details from the CSV and create categories programmatically.

The import script create categories and subcategories as shown below.Please find out how to import magento 2 products programmatically and other magento tutorials.

Import magento 2 categories programmatically

Step by step explanation

  • Initialise Script
  • Read CSV data
  • Import magento 2 categories

Initialise Script

Create a file named bulkimportcategory.php inside the script folder.For importing category images copy the images to the pub\media\catalog\category folder.

use MagentoFrameworkAppBootstrap;

include('../app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();

$url = MagentoFrameworkAppObjectManager::getInstance();
$storeManager = $url->get('MagentoStoreModelStoreManagerInterface');
$storeId = $storeManager->getStore()->getStoreId();

Read data from CSV

This step read the data from the sample CSV file and create an array.

function getCategories()
{
    $file = 'csv/categories.csv';
    $arrResult = array();
    $headers = false;
    $handle = fopen($file, "r");
    if (empty($handle) === false) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            if (!$headers) {
                $headers[] = $data;
            } else {
                $arrResult[] = $data;
            }
        }
        fclose($handle);
    }
    return $arrResult;
}

Import magento 2 categories programmatically

The following code iterate through the array and create the magento 2 categories programmatically.

/**
 * 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->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;

}

Click here to find out how to import categories magento 1 programmatically.

Share this Tutorial

Leave a Reply

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

*