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.

<?php 
 
/**
 * 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/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
 
$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.
{ 
  node_save($node);
  echo "Node with nid " . $node->nid . " saved!\n";
  echo "<pre>";
    print_r($node);
  echo "</pre>";
}
 
?>

Reference: http://fooninja.net/2011/04/13/guide-to-programmatic-node-creation-in-drupal-7/

About the author

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