Run drupal code outside of module: Create a node

By xngo on March 13, 2014

Here is an example of Drupal code that you can run outside of module. It will create an Article node. Put the code below in your Drupal root directory, and execute it either through the browser or from the command line.

 * The 4 lines below are needed so that your drupal code can be executed.
define('DRUPAL_ROOT', getcwd());
$_SERVER['REMOTE_ADDR'] = "localhost"; // Necessary if running from command line
require_once DRUPAL_ROOT . '/includes/';
$node = new stdClass();     // Create a new node object
$node->type = "article";    // Or page, or whatever content type you like
node_object_prepare($node); // Set some default values
$node->title    = "Node title " . date('Y-m-d H:i:s');
$node->language = LANGUAGE_NONE; // Or e.g. 'en' if locale is enabled
$node->uid = 1; // UID of the author of the node; or use $node->name
$bodytext = "This is text for the body of the node.";
$node->body[$node->language][0]['value'] = $bodytext;
if($node = node_submit($node)) // Prepare node for saving.
  echo "Node with nid " . $node->nid . " saved!\n";
  echo "<pre>";
  echo "</pre>";


About the author

Xuan Ngo is the founder of He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.