Magento 2 – How to programmatically set a new parent for a category?

Magento 2 have the built in category move() method which do the magic of moving the category including updating the parent id, moving the products, set new category URL, clear cache tags, reindex URLs list many more stuff.

Model Class Path :

/<Magento Directory>/vendor/magento/module-catalog/Model/Category.php

    /**
     * Move category
     *
     * @param  int $parentId new parent category id
     * @param  null|int $afterCategoryId category id after which we have put current category
     * @return $this
     * @throws \Magento\Framework\Exception\LocalizedException|\Exception
     */
    public function move($parentId, $afterCategoryId)
$categoryCollectionFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory');
$categoryId = '9';
$category = $categoryCollectionFactory->create()->load($categoryId);
$category->move(2, null); // 2 is new Parent Id
BEFORE
AFTER

Leave a Reply

Your email address will not be published.