Articles


How to create a node programmatically in Drupal 7

How to create a node programmatically in Drupal 7



Posted byUttam Kotekar,1st Oct 2015

Drupal itself provides an interface (node/add) to create a node content for the specific content type. But sometimes we will come across some functionality in which we need to create a node programmatically. To do that below is a simple example which will create a node for the content type articles.


// Create a new node object
$node_object = new stdClass();
// Specify your content type
$node_object->type = 'articles';
// 'en' if locale is enabled
$node_object->language = LANGUAGE_NONE;
// prepare the object and set default values
node_object_prepare($node_object);  
 
$node_object->title = 'Your node title';
$node_object->body[$node_object->language][0]['value'] = "Body Description";
$node_object->body[$node_object->language][0]['summary'] = text_summary("Body Description");
$node_object->body[$node_object->language][0]['format'] = 'full_html';
// (1 or 0): published or unpublished
$node_object->status = 1;
// (1 or 0): promoted to front page or not
$node_object->promote = 0;
// (1 or 0): sticky at top of lists or not 
$node_object->sticky = 0; 
// 2 = comments open, 1 = comments closed, 0 = comments hidden 
$node_object->comment = 1;
// Add author of the node
$node_object->uid = 1;
 
$path = 'articles/test-' . date('YmdHis');
$node_object->path = array('alias' => $path);
// Save the node
node_save($node_object);

That's it. Hope this short article has been helpful. Use the comment box below to share your views and doubts about this article here.

Categories