Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy and Paste Category in Magento

Tags:

php

magento

I want to copy my first category to a second category in Magento. What should I do?

Thanks, Wesley.

like image 932
Wesley Avatar asked Jun 17 '10 18:06

Wesley


3 Answers

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();
like image 173
joksnet Avatar answered Sep 18 '22 22:09

joksnet


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

like image 43
Elzo Valugi Avatar answered Sep 17 '22 22:09

Elzo Valugi


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.

like image 44
Mondane Avatar answered Sep 20 '22 22:09

Mondane