Last updated October 12, 2009. Created by bsenftner on October 12, 2009.
Log in to edit this page.

Sometimes it's useful to programmatically create a node. There are at least two methods, and here's one appropriate for the most basic of content types, the page:

  $newnode = new stdClass();
  $newnode->title = 'title';
  $newnode->body = 'whatever full html you like';
  global $user;
  $newnode->uid = $user->uid;
  $newnode->name = $user->name;
  $newnode->type = 'page';
  $newNode->format = 2;     // 1 means filtered html, 2 means full html, 3 is php
  $newnode->status = 1;     // 1 means published
  $newnode->promote = 0;
  $newnode = node_submit( $newnode );
  node_save( $newnode );

The above is good for story content type nodes too, but once one starts dealing with more complex content types, ones that require the user to fill out a form to create a node of that type, the above logic is lacking. See http://drupal.org/node/293663 for an example using drupal_execute(); a technique able to simulate the user filling out forms.

Looking for support? Visit the Drupal.org forums, or join #drupal-support in IRC.

Comments

Hey guys,

How to achieve that in Drupal 7?

its pretty much the same except for the following change:

$newnode->body =array('und'=>array(array('value'=> 'body')));

this code must insert in function (function modulename(){ instruction}) or what?

Hey guys,
How to programatically create a simple 'product' node of ubercart and how use the taxonomy reference term?

What's the D7 version of
$newNode->format = 2;

?

ꦱꦠꦽꦶꦪ