As part of a module update (for a D6 site) we had a requirement to populate a newly created node type from existing content.

The Solution

Multiple searches later (thanks Google!) the solution was offered by the blog post using Drupals API to batch script your Drupal site.

In a nutshell, the solution had 6 main elements:

  • a loop to extract the nodes 
  • node_load to get the full node object
  • an edit to change the node type
  • initialise the (new) node id and revision number
  • a node_submit (to do the Drupal form hooks magic) - optionally include a validation check!
  • a node_save to save the new content

It was also suggested that (perhaps) node validation on the $node object could be included but I didn't do that bit.

Show me the code

Anyway here's the code:

  $sql = "SELECT nid FROM node WHERE node_type IN (... list of node types ...) ORDER BY 1";
  if ($qry = db_query($sql)){
    while ($node = db_fetch_object($qry)) {
      $node  = node_load($node->nid);
      switch ($node->type) {
        ...selection to change the node type...
        $node->type = 'my new content type';
        ...
      }
      $node->nid = 0;
      $node->vid = null;
      $node = node_submit($node);
      // optional validation - only save if validated
      // if (!$node->validated) continue;
      node_save($node);
      // assume it works!
      drupal_set_message('New node '.$node->nid);
    }
  }

And voila - new nodes created!!

Tags: