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.

Comments

devoted.designer’s picture

Hey guys,

How to achieve that in Drupal 7?

anubhav.sahoo’s picture

its pretty much the same except for the following change:

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

utilisateur_drupal’s picture

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

utilisateur_drupal’s picture

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

wel3kxial’s picture

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

?

bawoor’s picture

ꦱꦠꦽꦶꦪ