Drupal 7: How to save a node programmatically and add an image field from a public URL

March 18, 2018

Introduction

I have a content type, which has an image field. I want to create many of these nodes programmatically.

Note: I have public URLs of these images, which I want to save.

Code to create Node

``` function _prepareImageObj($imageUrl) { if (!$imageUrl) { return FALSE; } $imageRes = drupal_http_request($imageUrl); if ($imageRes->code != 200) { return FALSE; } //prepare target path on disk $targetPath = 'public://prefix_' . date('Y').'/'.date('m'); file_prepare_directory($targetPath, FILE_CREATE_DIRECTORY); $imageFile = file_save_data($imageRes->data, $targetPath, FILE_EXISTS_REPLACE);

return $imageFile; } function save_my_node($valueArray) { $node = new stdClass(); $node->title = $valueArray->title $node->type = ‘my_content_type’; node_object_prepare($node);

$node->language = LANGUAGE_NONE; $node->uid = 1; //see if you want to use another user, or logged in user $node->status = 1; $node->promote = 0; $node->comment = 1; //comments closed $node->sticky = 0;

$node->body[$node->language][0][‘value’] = $valueArray->description; $node->body[$node->language][0][‘format’] = filter_default_format(); $imageObj = _prepareImageObj($valueArray->imageUrl); if (!$imageObj) { return false; } $node->field_image[$node->language][0] = (array)$imageObj;

// Prepare node for saving if ($node = node_submit($node)) { node_save($node);

print "\nNode saved, nid: ".$node->nid . ", videoId: ".$youtube_doc['_id'];

} else { print ‘Error’; } }


You can customize this code for more robust error handling.

Enjoy.

Similar Posts

Latest Posts