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 savemynode($valueArray) { $node = new stdClass(); $node->title = $valueArray->title $node->type = ‘mycontenttype’; nodeobjectprepare($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’] = filterdefaultformat(); $imageObj = prepareImageObj($valueArray->imageUrl); if (!$imageObj) { return false; } $node->fieldimage[$node->language][0] = (array)$imageObj;

// Prepare node for saving if ($node = nodesubmit($node)) { nodesave($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