Sometimes you want to create a page or a story, or any other node-based piece of content (but not content-type) programmatically. I’ve searched for explanation, and once again, when I can’t find something fast, I share it here. In this case I had to have some conversations.
It’s quite simple. Turns out Drupal uses php standard class as the base for its nodes.
Here’s how you build a node type page.
$newnode->title = 'Welcome';
$newnode->body = "This is the welcome page for your site. Replace this text with whichever content you'd like to use for your welcome page.";
global $user;
$newnode->uid = $user->uid;
$newnode->type = 'page';
$newnode->status = 1;
$newnode->promote = 0;
node_save($newnode);
Everything else is done just like that.
fifth line requires semi-colon ‘;’
it’s supposed to be: global $user;
(although php wouldn’t care about spaces)
Could you clarify where does this code go? in a file by itself? how does it communicate with Drupal?
Theoretically, you could put it anywhere where drupal runs php (even evaluated blocks with php code), but ideally, you should put this code into your module. When you start a new drupal website, you should always start at least one module to put all your custom functionality into it. For example, you might need this to run on hook_nodeapi (to respond to some drupal’s event), or on hook_menu callback, or whatever you please.
great snippet! This seems to update node and node_revisions. Is there a quick way to retrieve new node numbers to apply them to a custom content table?
I was wondering if there was just a plugin that would do this. Thanks for the tip.
I found this code very helpful. I wanted to add to it showing how you can add values to CCK fields:
$newnode->field_custom_field = array(array(‘value’ => ‘Custom Value Here’));
Thanks.
Drupal is great, but sometimes its documentation lacks the practical parts a little, IMHO.
This snippet clarifies a lot. Really useful.
Thank you a lot about very beneficial to my work was very useful thank you
Nice but how to set default values for content type fields. Nobody on the web explain it. I know node_object_prepare but it fill only sticky, … default values. What to do for custom fields
Thanks