7

I have around 500+ categories in my csv.

I'm trying to import only categories using csv.

Can anyone knows how to import only categories in magento 2 using csv?

2
  • Have you get solution of import export categories ? Jun 12, 2019 at 11:55
  • I am also facing issue in export categories. Could you please let me know if you have get any solution of export categories in csv? your help would be appreciated. Thanks Jun 13, 2019 at 5:55

2 Answers 2

0

As per your requirement, you can check out this - https://store.webkul.com/magento2-category-bulk-upload.html

This will help you to import and export a bulk number of categories on the store.

0

Here is a link to import categories from csv programmatically.

Step by step explanation

  1. Initialise Script
  2. Read CSV data
  3. 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 Magento\Framework\App\Bootstrap;
 
include('../app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
 
$url = MagentoFrameworkAppObjectManager::getInstance();
$storeManager = $url->get('Magento\Store\Model\StoreManagerInterface');
$storeId = $storeManager->getStore()->getStoreId();

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

function getProducts()
{
    $file = 'csv/products.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->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;
 
}

Sample CSV Data :

ID,ParentID,Name,top,columns,sort_order,Image,date_added,date_modified,language_id,seo_keyword,description,meta_description,meta_keywords,store_ids,layout,Status
100,0,Jewellery Boxes,,,,data/100-0-jewelleryboxes.jpg,,,,Jewellery Boxes,,,,,,TRUE
106,100,Leatherette Boxes,,,,data/106-100-leatheretteboxes.jpg,,,,Leatherette Boxes,,,,,,TRUE
4
  • can you please tell me the sample format of csv?
    – Ronak
    Dec 7, 2018 at 7:21
  • I have updated the answer with the sample CSV data. save it in categories.csv
    – nikin
    Dec 7, 2018 at 7:28
  • @Ronak Did this help you ?
    – nikin
    Dec 8, 2018 at 4:09
  • @nikin Please check this question and gives solution if you have idea. magento.stackexchange.com/questions/277997/… Jun 12, 2019 at 11:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.