[Drupal] How to add a file to the image field of a node programmatically in Drupal 6

| | 2 min read

I have a few images in a folder on a Drupal site I was recently working on. The Drupal site also had a content type that contained a title and an image field and I had a requirement to create a node for each of these images. Read on to find out how to add a file to the image field of a node programmatically in Drupal 6.

This is an one time process. So I have created a menu for this and in the page callback of this menu I have added code to create programmatically a node and to add file to the image field of node. The following is the code I have added in the page callback.

  
    // Get path to the images directory.
    $image_dir = drupal_get_path('module', 'mymodule').'/images/';
    // Get all image paths in the images directory as an array
    $call_imgs = glob($image_dir.'*.{jpg,jpeg,png,gif}',GLOB_BRACE);
    // Now add the images to the image field of node.
    foreach($call_imgs as $img) {
      $node = new stdClass;
      $node->type = 'my_content_type';
      $img_info = pathinfo($img);
      $field = field_file_save_file($img, array(), file_directory_path()); // Saves the file but in temporary status.
      $file_obj = (object) $field;
      file_set_status($file_obj, 1); // Making the file status permanent.
      $node->title = $img_info['filename']; // Setting the node title as the image filename.
      $node->field_image[0]['fid'] = $file_obj->fid; // Setting the image fid to the image field of the node.
      $account = $GLOBALS['user']; 
      $node->uid = $account->uid; // Setting the current user as the author of the node.
      node_save($node); // Saving the node.
     }
  

The above code does the following

  • Read all images from the images directory and save the files using field_file_save_file.
  • Setting the file status permanent using file_set_status function.
  • Adding the image to the node object.