Fork me on GitHub

How to build a node in Drupal programmatically

Submitted by hakunin on Thu, 06/07/2007 - 16:57

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.

Anonymous's picture

blogging on drupal

Is drupal a new thing? Or something that is older, because I have never heard of it before and im trying to find out.

Anonymous's picture

Where does this code go?

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

hakunin's picture

Theoretically, you could put

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.

Anonymous's picture

fifth line requires

fifth line requires semi-colon ';'

hakunin's picture

it's supposed to be: global

it's supposed to be:
global $user;

(although php wouldn't care about spaces)

Post new comment

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account, used to display your avatar.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <pre>, <bash>, <css>, <drupal5>, <drupal6>, <html4strict>, <ini>, <javascript>, <mysql>, <php>, <rails>, <ruby>, <sql>, <xml>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.