How do I move a category to another category with all child categories?
I have tried the following solution:
$nodeId = 2269;
$parentId = 2268;
$tree = Mage::getResourceModel('catalog/category_tree')->load();
$node = $tree->getNodeById($nodeId);
$parentNode = $tree->getNodeById($parentId);
$parentChildren = explode(',', $parentNode->getChildren());
$afterId = array_pop($parentChildren);
$prevNode = $tree->getNodeById($afterId);
if (!$prevNode || !$prevNode->getId()) {
$prevNode = null;
}
$tree->move($node, $parentNode, $prevNode);
However my result is somewhat twisted. If I move to the root-category the move works, but if I move to a child-category I get faulty results and disappearing categories.
These are the values of the field path in the database:
Old: 1/2/3/2175/2269
New: 1/2/3/2175/2226/2268/2269
Correct: 1/2/3/2226/2268/2269
The solution was quite simple, this one doesn't mess up the paths. However it feels like this method is slower.
$categoryId = 2269;
$parentId = 2268;
$category = Mage::getModel('catalog/category')->load($categoryId);
$category->move($parentId, null);
$parent = Mage::getModel('catalog/category')->load('REPLACE_WITH_PARENT_ID');
$category = Mage::getModel('catalog/category');
$category->addData(array('name' => 'YOUR_CATEGORY_NAME', 'path' => $parent->getPath()));
$category->save();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With