Drupal 6: Programmatically create any node type using drupal_execute

Here are some tips on how to create a node programmatically in a Drupal module. The safest way to create a node is to use the drupal_execute() function which simulates the submission of a form. This function accepts a variable number of arguments: 1) $form_id; 2) $form_state; and 3) any additional arguments. When creating a new node, the 3rd argument should be a $node object.

The $form_id should be formatted: NODETYPE_node_form. To confirm this, you could use hook_form_alter to show the form IDs for the current page (NOTE: you’ll have to be on node/add/NODETYPE to display the node form ID).

<?php
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  echo $form_id . "<BR>";
}
?>

For the second argument, you’ll have to create an array that contains $form_state values (the data submitted from the node/add/NODETYPE form). Here is a basic $form_state array:

<?php
$form_state = array();
$form_state['values'] = array(
  'title' => t('MYTITLE'),
  'body' => t('MYBODY'),
  'name' => $GLOBALS['user']->name,
  'op' => t('Save'),
);
?>

If you are creating a more complex node type, you’ll want to include more information in in the $form_state[‘values’] array. I find it helpful to view the submitted node form data using the following code:

<?php
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  // ensure we are modifying the right node type
  if ($form_id == 'NODETYPE_node_form') {
    // add an additional validation handler
    $form['#validate'][] = '_MYMODULE_node_form_validate';
  }
}

function _MYMODULE_node_form_validate($form, &$form_state) {
  // display the submitted data and then die
  echo "<pre>";
  print_r($form_state['values']);
  echo "</pre>";
  die;
}
?>

Now, if you create a test node (node/add/NODETYPE), you’ll see the data that’s being submitted from the form. NOTE: be sure to remove these two functions when you are familiar with the structure of the $form_state variable.

The 3rd argument will be a (mostly) empty $node object containing the node type:

<?php
$node = new StdClass();
$node->type = 'NODETYPE';
?>

Here’s a code snippet that shows all the pieces together:

<?php
// create $form_state
$form_state = array();
$form_state['values'] = array(
  'title' => t('MYTITLE'),
  'body' => t('MYBODY'),
  'name' => $GLOBALS['user']->name,
  'op' => t('Save'),
);

// create $node
$node = (object) NULL;
$node->type = 'NODETYPE';

// include node file, necessary for node generation
module_load_include('inc', 'node', 'node.pages');

// create node using drupal_execute
drupal_execute('NODETYPE_node_form', $form_state, $node);
?>

Updated: