How To Programmatically Export Category Name With Parent Category Name Magento 2

Written by Jigar Patel

Dec 20, 2021

How To Programmatically Export Category Name With Parent Category Name Magento 2

Magento 2 Category Trees structure indicates about category parent and subcategories. Get Category tree collection by the specific root category id.

Magento has the interface to get the category tree by the Magento\Catalog\Api\CategoryManagementInterface with getTree() method.

The root category counts as the first level, although it doesn’t appear in the menu. The maximum number of levels that are available in the top navigation is determined by the configuration. In addition, there might be a limit to the number of menu levels that are supported by your store theme. For example, the sample Luma theme supports up to five levels, including the root.

Counting menu levels

  • Level 1 The first level is the root category, which in the sample data is named “Default Category.” The root is a container for the menu, and its name does not appear as an option in the menu.
  • Level 2 On a desktop display, the top navigation is the main menu that appears across the top of the page. On a mobile device, the main menu typically appears as a fly-out menu of options. The second-level options in the Luma store are What’s New, Women, Men, Gear, Training, and Sale.
  • Level 3 The third-level appears below each main menu option. For example, under Women, the third-level options are Tops and Bottoms.
  • Level 4 The fourth-level options are subcategories that fly out from a third-level option. For example, under Tops, the fourth level menu options are Jackets, Hoodies & Sweatshirts, Tees, and Bras & Tanks.

Read This: Create, Update and Remove Custom Category Attributes Using UpgradeData.php In Magento 2

Programmatically export category name with parent category name create a PHP file in Magento root directory using following code. Do not forget to specify the category root id you want to set inside the code.

Step To Programmatically Export Category Name With Parent Category Name Magento 2:

<?php

use Magento\Framework\App\Bootstrap;

require '../app/bootstrap.php';
ini_set('display_errors', 1);
$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=category_level.csv");
header("Pragma: no-cache");
header("Expires: 0");

$categoryData = [];
$rootCategoryId = 2;
$categoryManagement = $objectManager->get('Magento\Catalog\Api\CategoryManagementInterface');
$getSubCategory = getCategoryData($categoryManagement, $rootCategoryId);
foreach ($getSubCategory->getChildrenData() as $category) {
    $cat = $category->getName();
    $categoryData[$category->getId()] = [
        'name' => $category->getName(),
        'url' => $category->getUrl()
    ];
    if (count($category->getChildrenData())) {
        $getSubCategoryLevelDown = getCategoryData($categoryManagement, $category->getId());
        foreach ($getSubCategoryLevelDown->getChildrenData() as $subcategoryl1) {
            $cat1 = $cat . ',' . $subcategoryl1->getName();
            $categoryData[$subcategoryl1->getId()] = [
                'name' => $cat . ',' . $subcategoryl1->getName(),
                'url' => $subcategoryl1->getUrl()
            ];
            if (count($subcategoryl1->getChildrenData())) {
                $getSubCategoryLevelDownl = getCategoryData($categoryManagement, $subcategoryl1->getId());
                foreach ($getSubCategoryLevelDownl->getChildrenData() as $subcategoryl2) {
                    $cat2 = $cat1 . ',' . $subcategoryl2->getName();
                    $categoryData[$subcategoryl2->getId()] = [
                        'name' => $cat1 . ',' . $subcategoryl2->getName(),
                        'url' => $subcategoryl2->getUrl()
                    ];
                    if (count($subcategoryl2->getChildrenData())) {
                        $getSubCategoryLevelDownl = getCategoryData($categoryManagement, $subcategoryl2->getId());
                        foreach ($getSubCategoryLevelDownl->getChildrenData() as $subcategoryl3) {
                            $cat3 = $cat2 . ',' . $subcategoryl3->getName();
                            $categoryData[$subcategoryl3->getId()] = [
                                'name' => $cat2 . ',' . $subcategoryl3->getName(),
                                'url' => $subcategoryl2->getUrl()
                            ];

                        }
                    }

                }
            }
        }
    }
}
/*echo "<prE>";
print_r($categoryData);
exit;*/
$output = fopen('php://output', 'w');
fputcsv($output, array('Id', 'Level 1', 'Level 2', 'Level 3', 'Level 4'));
foreach ($categoryData as $datak => $datav) {
    $catLevel = $datak . ',' . $datav['name'];
    $catLevel = explode(',', $catLevel);
    fputcsv($output, $catLevel);
    //echo $datak . ',' . $datav['name'] . '<br>';
}
fclose($output);
exit;
function getCategoryData($categoryManagement, $categoryId)
{
    try {
        $getSubCategory = $categoryManagement->getTree($categoryId);
    } catch (Exception $exception) {
        $getSubCategory = null;
    }
    return $getSubCategory;
}

categoryManagement is an instance of \Magento\Catalog\Api\CategoryManagementInterface

getTree() is the desired array of the category tree.

Result:-

How To Programmatically Export Category Name With Parent Category Name Magento 2

Successfully executing this script you get category name with parent category name.

Hope this instruction will be helpful for you.

Jigar Patel

Author

We can help you with

  • Dedicated Team
  • Setup Extended Team
  • Product Development
  • Custom App Development

Schedule a Developer Interview And Get 7 Days Risk-Free Trial

Fill out This Form and one of Our Technical Experts will Contact you Within 12 Hours.

    Google
    |

    4.8

    Google
    |

    4.8

    Google
    |

    4.9

    Google
    |

    4.8

    Google
    |

    4.9

    Copyright © 2024 DOLPHIN WEB SOLUTION. All rights reserved.

    TO TOP