Programmatically create a CCK node | Eric's Drupal Blog

Programmatically create a CCK node

Eric's picture

Here's my code snippet, I use it all the time. NOTE: replace {BLAH} with your data.

<?php
// add node properties
$newNode = (object) NULL;
$newNode->type = '{NODE_TYPE}';
$newNode->title = '{NODE_TITLE}'
$newNode->uid = {USER_ID};
$newNode->created = strtotime("now");
$newNode->changed = strtotime("now");
$newNode->status = 1;
$newNode->comment = 0;
$newNode->promote = 0;
$newNode->moderate = 0;
$newNode->sticky = 0;

// add CCK field data
$newNode->field_{YOUR_CUSTOM_FIELD_1}[0]['value'] = '{DATA_1}';
$newNode->field_{YOUR_CUSTOM_FIELD_2}[0]['value'] = '{DATA_2}';

// save node
node_save($newNode);
?>

NOTE: the structure of the CCK fields can vary. Here's one way to see the structure of an already created CCK node...

<?php
$sampleNode
= node_load('{ALREADY_CREATED_CCK_NODE_ID}');
echo
"<PRE>" . print_r($sampleNode, TRUE) . "</pre>";
?>

gradient spacer

Comments...

Clear and concise

Excellent work! I can definitely use this. filefield and imagefield cck fields are gonna be a bit tricky though ;-)

Cheers,

Richard
(siliconmeadow)
http://drupal.org/user/55284

Eric's picture

absolutely

I have been struggling with a migration tool to import a photo gallery into Drupal for quite some time. In the end, I had great success with node_import (which now supports imagefields)!

You just save my life again

Thanks for the succint and straigthforward code.Keep it simple.....you are good.

Chachrist Srisuwanrat

where to run this script ?

where to run this script ?
just put some where in drupal installation folder and execute thru
for example http://mydomain.com/bulknodecreate.php

Eric's picture

module

I pulled that code from a module that I wrote.

You might also want to check out Drush: http://drupal.org/project/drush