How to build a node in Drupal programmatically

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 = new stdClass();
$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.

4 responses to “How to build a node in Drupal programmatically”

  1. Familiar

    fifth line requires semi-colon ‘;’

  2. Anonymous

    Could you clarify where does this code go? in a file by itself? how does it communicate with Drupal?

Leave a Reply