Create node with php in Drupal 7

Creating a node with PHP in Drupal 7 is easy. This can be used to insert one node from a custom form or to insert a batch of nodes from an array of data.

Just follow these instructions to populate a node with PHP.

// start with a blank object
$node = new stdClass();
$node->type = 'node-type';
// adds defaults for node type
node_object_prepare($node);

$node->title = 'Any title';
// set language to default 'und'
$node->language = LANGUAGE_NONE;

// sets node author (can use $node->name instead)
$node->uid = 1;

// set the body field
$node->body[$node->language][0]['value'] = 'text';
$node->body[$node->language][0]['format'] = 'filtered_html';

// most other fields can be added this way
$node->field_name[$node->language][0]['value'] = 'value';

// updates author and publish date
node_submit($node);
node_save($node);
Category: