I want to copy my first category to a second category in Magento. What should I do?
Thanks, Wesley.
By code:
<?php
$category = Mage::getModel('catalog/category')
->load(123); // The ID of the category you want to copy.
$copy = clone $category;
$copy->setId(null) // Remove the ID.
->save();
If you want to do it in a programmatic way you can use the Magento API. Use:
catalog_category.info - to read a category
catalog_category.create - to create a new one by copying data from existing.
Here are the docs for category API
I wouldn't clone the category object, but rather do something like this (using the Magento API - http://www.magentocommerce.com/wiki/doc/webservices-api/catalog_category ):
get the category which must be copied
$source_category = Mage::getModel('catalog/category')->load($id);
Create a new category using the API
$CategoryApi = new Mage_Catalog_Model_Category_Api();
$parent_id = /* Location for the new category */
$new_category_id = $CategoryApi->create(
$parent_id,
array(
/* Attributes to fill with source category values. */
)
);
Get the source category products and place them in the new category, again with the API.
$products = $CategoryApi->assignedProducts(source_category->getId());
foreach($products as $product)
{
$CategoryApi->assignProduct($product->getId())
}
Above must be done recursively for each subcategory.
Note: Using the API ensures your code will still work when you upgrade the Magento core.
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