Move Category from one position to another using the move() method from the catalog module.
Function Definition from the interface Magento\Catalog\Api\CategoryManagementInterface,
/** * @param int $categoryId * @param int $parentId * @param int $afterId * @return bool * @throws \Magento\Framework\Exception\LocalizedException * @throws \Magento\Framework\Exception\NoSuchEntityException */ public function move($categoryId, $parentId, $afterId = null);
$categoryId indicates the Category Id to move,
$parentId indicates the Parent id to move your category,
$afterId default value is null. The parameter is used to move your category after a specific category, at that time you have to pass category id value for this argument.
When you have $afterId value is specific category id and not null value, you have to pass $parentId value will be 2(Default Category)
<?php
namespace Jesadiya\MoveCategory\Model;
use Exception;
use Magento\Catalog\Api\CategoryManagementInterface;
class MoveCategory
{
/**
* @var CategoryManagementInterface
*/
private $categoryManagement;
public function __construct(
CategoryManagementInterface $categoryManagement
) {
$this->categoryManagement = $categoryManagement;
}
/**
* Move Category
*
* @return CategoryTreeInterface
*/
public function moveCategory()
{
$isCategoryMoveSuccess = false;
try {
$categoryId = 40;
$parentId = 2;
$afterId = 20;
$isCategoryMoveSuccess = $this->categoryManagement->move($categoryId, $parentId, $afterId);
} catch (Exception $exception) {
throw new Exception($exception->getMessage());
}
return $isCategoryMoveSuccess;
}
}
Call the method from the PHP class to move the category position,
$isCategoryMove = $this->moveCategory(); echo "<pre>"; print_r($category->debug());
Output:
Boolean
