Drupal 7 – Create node programmatically

The following piece of code creates a new node of a subscriber content type. This subscriber has two textfields which called First Name and Last Name. In this example, we make use of the node_object_prepare() function which helps preparing the node object.

// Create the new node object
$subscriber = new StdClass();
$subscriber->type = 'subscriber';
$subscriber->title = $form['email_address']['#value'];
$subscriber->language = LANGUAGE_NONE;
$subscriber->uid = 1;
$subscriber->date = format_date($subscriber->created, 'custom', 'Y-m-d H:i:s O');

// Add field data
$subscriber->field_last_name['und'][0]['value'] = $form['last_name']['#value'];
$subscriber->field_first_name['und'][0]['value'] = $form['first_name']['#value'];

// Save node

// Greetings
drupal_set_message('A subscriber is created.');

Done =)



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.