Insert a new node programatically?
jake67890 - January 9, 2008 - 05:25
What is the recommended way to insert a new node into drupal w/o using the admin interface? Basically I need to create new pages automatically & make sure they are appearing in the sitemap as well.
I've been able to insert a new node using the db abstraction api, however i know I am missing some things because the new page doesn't show in the sitemap or anything. I'm hoping there is a function like "insert_node" or whatever that I could use instead of trying to reverse engineer what is happening in the DB?
thanks for any assistance or just pointing me to the correct set of functions.

The best option is ...
to use the drupal_execute command and submit a node_form ... this snippet
$node_type = 'page'; //change this to match the type of node you want
global $user; //this code will use the current logged in user as the nodes author
$form_id = $node_type.'_node_form';
$node = array('uid' => $user->uid, 'name' => $user->name, 'type' => $node_type);
$edit=array();
$edit['title']='Node title';
$edit['body']='Body content of the node'
//optionally add taxonomy terms
$edit['taxonomy'][$vocab_id)][]=$term_id;
$edit['format'] = 1;
$edit['name'] = $user->name;
//make the call to drupal execute
$url = drupal_execute($form_id,$edit,$node);
One thing to remember is that the return value from drupal execute is the path to the new node - this is not desperately useful as in many cases you actually need the nid ... you can obviously do a quick lookup on the url to work out the node id though ...
Hope this helps ...
Mike,
Computerminds offer Drupal development, consulting and training
Version 4.7.6
thank you for the reply. Unfortunately I just discovered that I'm running version 4.7.6, even though I had been told we are on version 5!
If anybody knows how to do that using version 4, that would be a huge help. Sorry for posting in the wrong topic.
Oooo ...
In that case you need to use
node_save- just build the node up and then make a call to node_save when your ready - something like$node->title='Your title';$node->body='dfhskjdhfdskf';
$node->uid=1;
node_save($node);
Cheers,
Mike,
Computerminds offer Drupal development, consulting and training
node_factory to insert nodes programatically
The module node_factory might provide an good way to do this: http://drupal.org/project/node_factory
It's still in beta and I personally have not used it in production, but I think it is the way to go forward: node creation is a complicated process with small changes from Drupal version to version, so it would be nice if this functionality could be provided by a simple interface through a well maintained module.