How to Move Category Position Programmatically in Magento 2?

How to Move Category Position Programmatically in Magento 2

Hello Magento Friends,

In today’s instructional guide, I will explain How to Move the Category Position Programmatically in Magento 2?

A Magento 2 store contains various categories to classify the products based on their type. The category comprises various subcategories and products. You can quickly move subcategories in Magento 2 by drag-and-drop from the Admin Panel. Another way to move the category position is by executing it programmatically.

Let’s see how to move the category position from one parent category to another parent category along with its products programmatically in Magento 2.

Steps to Move Category Position Programmatically in Magento 2:

Category position before running the script

category position - before

Step 1: Create a file in your Magento root directory at the below path. 

magento_root_directory\Changecategoryposition.php

Now add the code as follows

<?php
use Magento\Framework\AppInterface;
try
{
    require_once __DIR__ . '/app/bootstrap.php';
} 
catch (\Exception $e) 
{
    echo 'Autoload error: ' . $e->getMessage();
    exit(1);
}
try
{
	$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
	$objectManager = $bootstrap->getObjectManager();
	$appState = $objectManager->get('\Magento\Framework\App\State');
	$appState->setAreaCode('frontend');
	
       $category = $objectManager->get('\Magento\Catalog\Api\CategoryManagementInterface');

	
	$categoryId = 5; //id of The category to be moved
        $parentId = 6; //id of parent category where the new category to move
        $afterId = 7; //id of category after which you want to move
        
        $CategoryMoveSuccess = $category->move($categoryId, $parentId, $afterId);	
        
        if($CategoryMoveSuccess)
        {
            echo "Successfully Move Category Position";
        }  
        else
        {
            echo "Not Move Category Position";	
        }
}
catch(\Exception $e)
{
	echo "Error : ".$e->getMessage();
}

?>

Step 2: After the above step, you will need to run the below-given URL.

https://yourdomain.com/Changecategoryposition.php 

Category position after running the script

category position - after

Conclusion:

This way, you can change the category position in Magento 2 programmatically. Alternatively, you can integrate Duplicate Categories Extension for Magento 2 to create a copy of the category.

Share your doubts with me in the comment box. Stay in touch with us for more Magento 2 solutions.

Happy Coding!

Previous Article

React Custom Hooks with Examples

Next Article

Magento 2 Extensions Digest April 2023 (New Release & Updates)

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨