Skip to main content
Create new node

Programmatically create a node in drupal 7

Steps for programmatically creating node in drupal7,
1. Create a new node object.
2. Save the object using the node_save() function.

Basic Node Creation :

$complaint_body = 'Your node complaint body text';
$node = new stdClass();  // Create a new node object
$node->type = 'company';  // Content type
$node->language = LANGUAGE_NONE;  // Or e.g. 'en' if locale is enabled
node_object_prepare($node);  //Set some default values

$node->title = 'Your node title';
$node->body[$node->language][0]['value'] = $complaint_body;
$node->body[$node->language][0]['summary'] = text_summary($complaint_body);
$node->body[$node->language][0]['format'] = 'full_html';

$node->status = 1;   // (1 or 0): published or unpublished
$node->promote = 0;  // (1 or 0): promoted to front page or not
$node->sticky = 0;  // (1 or 0): sticky at top of lists or not
$node->comment = 1;  // 2 = comments open, 1 = comments closed, 0 = comments hidden
// Add author of the node
$node->uid = 1;
// Set created date
$node->date = 'complaint_post_date';
$node->created = strtotime('complaint_post_date');

$path = 'content/mytest-' . date('YmdHis');
$node->path = array('alias' => $path);
// Save the node
node_save($node);

Add custom fields

$node->field_complaint_address[LANGUAGE_NONE][0]['value'] = 'This is custom cck filed to get complaint address';

Add a node reference to a node

$node->field_review_company_name[$node->language][0]['nid'] = 'company_node_id';

Add a term reference to a node

$node->field_company_industry[$node->language][0]['tid'] = 'company_term_id';

Add file / image fields

// Create image File object and associate with Image field.
$file = new StdClass();
$file->uid = 1;
$file->uri = $imagepath;
$file->filemime = file_get_mimetype($file->uri);
$file->status = 1;
$file->display = 1;
$file->description = "";  
$dest = file_default_scheme() . '://complaint_image_directory';
$file = file_copy($file, $dest);
$node->field_complaint_image[LANGUAGE_NONE][0] = (array)$file;


 

Comments