Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Attaching image files to nodes programmatically in Drupal 7

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 2.23k
    Comment on it

    Hi All,

    It is quite easy to add a node programmatically in Drupal 7. But it gets little bit complex when we need to add an image to this node as well.

    Use the following codebase to add an image to a node programmatically:

      global $user_id;
      $filename = 'myimage.jpg';
      $image_object = file_get_contents('url_of_your_image);
      $file = file_save_data($image_object, 'public://' . $filename, FILE_EXISTS_RENAME);
    
      $file->uid = $user->uid;
      $node->field_my_image[$node->language][0] = (array)$file;
      node_save($node);
    
    
      //If you want to save and existing image from drupal directory
      $filepath = drupal_realpath('misc/druplicon.png');
       // Create managed File object and associate with Image field.
        $file = (object) array(
          'uid' => 1,
          'uri' => $filepath,
          'filemime' => file_get_mimetype($filepath),
          'status' => 1,
        );    
       // We save the file to the root of the files directory.
       $file = file_copy($file, 'public://');
      $node->field_my_image[$node->language][0] = (array)$file;
      node_save($node);
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: