måndag 23 november 2009

Copy part of category tree to other node in Magento

Ever wanted to copy parts of the category tree to other nodes?

One of my current projects under development has hundreds of hundreds of categories. Each car model has 50 or so sub-categories. It would be really painful to create all of these for each model (25 models times 50 categories) so instead i created them once and then used Magentos XmlRpc API to copy them to each model.


require_once('Zend/XmlRpc/Client.php');

// Which id to copy children from
define('COPY_FROM', 1);

// Which id to copy to
define('COPY_TO', 40);

// Set it to your sites path
$api_path = 'http://magento.kontilint.se/api/xmlrpc'

// User andm api key defined in your magento installation
$api_user = 'magento_api';
$api_key = 'magento_key';

// Create a client
$client = new Zend_XmlRpc_Client($api_path);

// Login and get a session id
$session_id = $client->call('login', array($api_user, $api_key));

// Get categories
$categories = $client->call('call', array($session_id, 'catalog_category.tree', COPY_FROM));

// Copy categories
copy_categories($categories['children'], COPY_TO);

function copy_categories($categories, $parent) {
 // We need our session id and our client
 global $session_id;
 global $client;

 foreach ($categories as $category) {
  $new_id = $client->call('call', array($session_id, 'category.create', array($parent, array('name' => $category['name'], 'is_active' => 1, 'available_sort_by' => 'name', 'default_sort_by' => 'name'))));
  if ($new_id == null || (int)$new_id < 1) {
   die("Could not create category\n");
  }
  if (is_array($category['children'])) {
   copy_categories($category['children'], $new_id);
  }
 }
}

0 kommentarer: