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';
node_object_prepare($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
node_save($subscriber);

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

Done =)

Reference:

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s