Insert CCK image in to the node programmatically - Drupal API
In Drupal if you have cck image field in your node it gets harder to create node programmaticaly. Here is how you can do it using Drupal API and node_save function. You need to create image in the image field table. The image should be already uploaded on the server somwhere under the files folder. Once you insert the image information in to the image table you will get file id back. Than just pass this file id in to the node object.
Here is how you can get file id (fid):
let say your image is here
<drupal home>/files/images/myimg.jpeg
your code will look something like this:
<?php
$image_path = '/home/drupal/site/files/images/myimg.jpeg';
$image_info = image_get_info($image_path);
$name_arr = explode('/', $image_path );
$name = end($name_arr);
$file = array(
'uid' => 1,
'filename' => $name,
'filepath' => $image_path,
'filemime' => $image_info['mime_type'],
'filesize' => $image_info['file_size'],
'status' => FILE_STATUS_PERMANENT,
'timestamp' => time(),
);
drupal_write_record('files', $file);
$fid = $file['fid'];
?>
Once you got file id you can use it in the node object and cck field using node_save() function.
Here is the complete code with the bit to get file id put in to separate function:
$nid = 123;
$node = node_load($nid);
// add image to database
$imagepath = '/home/mynema/images/image.123.jpg';
$output .= write_image_info($imagepath, $fid);
// now add image to node
// this is the name of your image cck field
$node->field_oa_image[0]['fid'] = $fid;
node_save($node);
function write_image_info($image_path, &$fid){
if (file_exists($image_path)){
$image_info = image_get_info($image_path);
$name_arr = explode('/', $image_path );
$name = end($name_arr);
$file = array(
'uid' => 1,
'filename' => $name,
'filepath' => $image_path,
'filemime' => $image_info['mime_type'],
'filesize' => $image_info['file_size'],
'status' => FILE_STATUS_PERMANENT,
'timestamp' => time(),
);
drupal_write_record('files', $file);
print_dsm($file);
$fid = $file['fid'];
}
else{
$output .= '<p>image not found at this path: '.$image_path.'</p>';
}
return $output;
}
