I have this code

      $node = (object) array(

        'title' => 'Title',

        'body' => array(

          LANGUAGE_NONE => array(

            0 => array(

              'value' => 'Body Text',

              'summary' => 'Summary',

              'format' => 'filtered_html',

        'type' => 'article',
        'language' => LANGUAGE_NONE,

        'uid' => 1,


      $filepath = drupal_realpath('http://ppcdn.500px.org/52335278/cbc55dab399a4bd9caf7a27e9bb3564bc8458f65/3.jpg');

      $file = (object) array(
        'uid' => 1,
        'uri' => $filepath,
        'filemime' => file_get_mimetype($filepath),
        'status' => 1,

      $file = file_copy($file, 'public://');

      $node->field_image[LANGUAGE_NONE][0] = (array)$file;

      node_save((object) $node);

      $path['alias'] = 'our-great-dsk-node';
      $path['source'] = 'node/' . $node->nid;
      $path['language'] = LANGUAGE_NONE;


But can't understand where to use this code to create nodes programmatically in drupal 7 or how to use this code? To test i saved this as custom-posts.php in drupal root directory to see if this code works or not, but it gives a lot errors, so what to include?


To bootstrap, try adding the following lines of code to the top of your custom-posts.php file:

define('DRUPAL_ROOT', '/var/www/drupal7');
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';

Don't forget to update the path to your Drupal root folder.

|improve this answer|||||

Drupal is not bootstraped in your php file and its API is not available. Try to create a module and put your code in a hook_install() to try it out

|improve this answer|||||
  • include('./includes/bootstrap.inc'); also giving error.. – jenner beiy Nov 17 '13 at 12:44
  • You need the three first lines from your index.php for a full bootstrap – Pan Chrono Nov 17 '13 at 12:51

If you want to add custom code you should better create your custom module.

-- This is how you can create your custom module.

If you want a way to test your php code working or not, you can install devel module, once you install devel module,access yoursitenma.com/devel/php,basically devel opens a testing custom php codes at "devel/php" there you can execute your codes like in your case it is about creating custom nodes.

Try executing your node creating codes either with help of custom module or at "devel/php".As a note it will be better if you test your codes in chunks i.e. simply start with building node without having file field and path alias so your scope of debugging gets limited and clean and then can proceed stepwise.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.