Ask your Question

PEOPLE YOU MIGHT KNOW

gourav
gourav

Moradabad,  India
Lonnie
Lonnie

Jacobus,  United States
Praveen
Praveen

Software Developer

NOIDA,  India
William
William

Web Developer

Elkhart,  United States
Vivek
Vivek

PHP Developer

Noida,  India

Write to us

Ask Question

Move category programatically from one parent category to other parent category in Magento2

Sikha Goel
Move category programatically from one parent category to other parent category in Magento2

We have a category on root ie. rings child of default cateory, we want to move in another category i.e Accesories that is also on level2 (child of defualt category ).
<?php
define('MAGENTO_ROOT', getcwd());
$magentoroot = MAGENTO_ROOT;

use MagentoFrameworkAppBootstrap;
require_once($magentoroot.'/app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('MagentoFrameworkAppState');
$state->setAreaCode('adminhtml');
$categoryFactory  = $objectManager->create(MagentoCatalogModelCategoryFactory::class);

    $categoryID = 204;      // rings category which we need to move
    $currentParentId = 2;      // 2 is id of root default category 
    $parentId = 130;         // id of accesories category to which we will move rings category

 try {
            $storeId = 1;
            $error = false;
            $category = initCategory($categoryID, $storeId, $objectManager);
        
        if ($category === false) {
             throw new Exception(__('Category is not available for requested store.'));
        }

        $category->move($parentId, $currentParentId);

    } catch (MagentoFrameworkExceptionLocalizedException $e) {
          $error = true;
          $message = $e->getMessage();

    } catch (Exception $e) {
          $error = true;
         $message = 'something went wrong, please try again';
    }
        if (!$error) {

            $message = 'Category has been moved';
    }

function initCategory($categoryId, $storeId, $objectManager)
{
      $category = $objectManager->create(MagentoCatalogModelCategory::class);
      $category->setStoreId($storeId);
      if ($categoryId) {
          $category->load($categoryId);
    } 

    return $category;
}

Sikha Goel

Please rotate your device

We don't support landscape mode on your device. Please rotate to portrait mode for the best view of our site