Ask your Question

Discover our new Professionals

Bhuwan
Bhuwan

Intern PHP Developer

Dehradun,  India
Mintu
Mintu

Faridabad,  India
Randip
Randip

eCommerce Web Developer

Deerfield Beach,  United States
UDAYAKUMAR
UDAYAKUMAR

PHP devoloper

Bangalore,  India
rakesh
rakesh

Software Developer

Delhi,  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 Magento\Framework\App\Bootstrap;
require_once($magentoroot.'/app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('adminhtml');
$categoryFactory  = $objectManager->create(\Magento\Catalog\Model\CategoryFactory::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 (\Magento\Framework\Exception\LocalizedException $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(\Magento\Catalog\Model\Category::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