Convert nodes from one content type to another

Public

Two different methods converting (and moving data) from one content type to another

Get raw version
php
  1. /**
  2.  * Convert basic_page to Page and move the data too:
  3.  * Remember Add required field instances to page -content type first.
  4.  */
  5. function mymodule_update_7001(&$sandbox) {
  6. // Convert basic_page into page
  7. $node_type = db_query("UPDATE node SET type = 'page' WHERE type = 'basic_page';");
  8. $node_type->execute();
  9. watchdog('mymodule', t('Node type basic_page was converted into page'));
  10.  
  11. $type = "basic_page";
  12. $nodes = node_load_multiple(array(), array('type' => $type));
  13. foreach($nodes as $node){
  14. $node->type = 'page';
  15. // Make this change a new revision
  16. $node->revision = 1;
  17. $node->log = 'This node was programatically updated at ' . date('c');
  18. node_save($node);
  19. }
  20. }

The same functionality but running as batch operation

Get raw version
php
  1. /**
  2.  * Convert basic_page to Page and move the data too:
  3.  * Remember Add required field instances to page -content type first.
  4.  */
  5. function mymodule_update_7001(&$sandbox) {
  6. // If this is the first pass through this update function then set some variables.
  7. if (!isset($sandbox['total'])) {
  8. $result = db_query("SELECT nid FROM node WHERE type='basic_page'");
  9. $sandbox['total'] = $result->rowCount();
  10. $sandbox['current'] = 0;
  11. }
  12.  
  13. // How many nodes should be processed per pass.
  14. $nodes_per_pass = 10;
  15.  
  16. // Get the nodes to process during this pass.
  17. $result = db_query_range("SELECT nid FROM node WHERE type='basic_page'", $sandbox['current'], $nodes_per_pass);
  18. while ($row = $result->fetchAssoc()) {
  19. // Load the node, edit its type, and save the node.
  20. $node = node_load($row['nid']);
  21. $node->type = 'page';
  22. // Make this change a new revision
  23. $node->revision = 1;
  24. $node->log = 'This node was programatically updated at ' . date('c');
  25. node_save($node);
  26.  
  27. // Lets tell the site admin what we are doing. You could write to a log here, or a watchdog message or whatever...
  28. drupal_set_message(t('We processed node @nid', array('@nid' => $node->nid)));
  29.  
  30. // Increment "current" by 1.
  31. $sandbox['current']++;
  32. }
  33.  
  34. // Set the value for finished. If current == total then finished will be 1, signifying we are done.
  35. $sandbox['#finished'] = ($sandbox['current'] / $sandbox['total']);
  36.  
  37. if ($sandbox['finished'] === 1) {
  38. drupal_set_message(t('We processed @nodes nodes. DONE!!!', array('@nodes' => $sandbox['total'])));
  39. }
  40. }

Comments

drupby's picture

  1. // $sandbox['#finished'] ???
  2. $sandbox['finished'] = ($sandbox['current'] / $sandbox['total']);
Ken Colwell's picture

Thank you for this code... it saved me a lot of time!