Skip to content

Instantly share code, notes, and snippets.

@vishy93
Last active February 26, 2019 14:33
Show Gist options
  • Save vishy93/e44d774423a38ac39088b866f7e79cce to your computer and use it in GitHub Desktop.
Save vishy93/e44d774423a38ac39088b866f7e79cce to your computer and use it in GitHub Desktop.
Script to duplicate a target category along with it's sub-categories and products under another category.
<?php //can be run as root script
require '../app/Mage.php';
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$categoryId = 864; //Target Cat to copy
$baseCategoryId = 240; //Category to appear under
$category = Mage::getModel('catalog/category')->load($categoryId);
$defaultCategory = Mage::getModel('catalog/category')->load($baseCategoryId);
duplicate($category, $defaultCategory, 1);
function duplicate($categoryToClone, $parentCategory, $level)
{
// This will clone the clild and assign it to the new parent
$newCategory = clone $categoryToClone;
$newCategory->setPath($parentCategory->getPath())
->setParentId($parentCategory->getId())
->setId(null);
// Assign all products from the cloned category to the new
$newCategory->setPostedProducts($categoryToClone->getProductsPosition());
$newCategory->save();
// Applies the changes to the subcategories infinite levels
$subcategories = $categoryToClone->getChildrenCategories();
if (count($subcategories) > 0) {
foreach ($subcategories as $subcategory) {
duplicate($subcategory, $newCategory, ++$level);
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment