How to create and save a node programmatically
An example of how to create and save a node programmatically.
<?php
/**
* Creates a node
*/
function mymodule_create_task($task) {
global $user;
$node = new stdClass();
$node->type = "task";
$node->uid = $user->uid;
$node->title = check_plain($task['title']);
//Strip tags without
$allowed_tags = "<p><br><ul><ol><li><b><strong><i><em><a>";
$node->body = mymodule_strip_tags_attributes($task['body'], $allowed_tags, "href, rel");
$node->format = 2;
$node->status = 1;
//CCK fields
$node->field_t_zoho_task_id[0]['value'] = $task['field_t_zoho_task_id'];
$node->field_t_description[0]['value'] = $task['field_t_description'];
$node->field_t_campaign_id[0]['value'] = $task['campaign']['id'];
//Organic group OG
$node->og_groups[$og_group] = $og_group;
$node->og_groups_both[$og_group] = $og_group_name;
$node->og_public = 0;
node_save($node);
watchdog("mymodule_create_task", "<pre>".print_r($node, TRUE)."</pre>".__FILE__);
return $node;
}
/**
* A modified strip tags function filtering
* tags attribute as well and keeps allowed attributes
*
* @param unknown_type $string
* @param unknown_type $allowtags
* @param unknown_type $allowattributes
* @return unknown
*/
function mymodule_strip_tags_attributes($string,$allowtags=NULL,$allowattributes=""){
$string = strip_tags($string,$allowtags);
if (!is_null($allowattributes)) {
if(!is_array($allowattributes))
$allowattributes = explode(",",$allowattributes);
if(is_array($allowattributes))
$allowattributes = implode(")(?<!",$allowattributes);
if (strlen($allowattributes) > 0)
$allowattributes = "(?<!".$allowattributes.")";
$string = preg_replace_callback("/<[^>]*>/i",create_function(
'$matches',
'return preg_replace("/ [^ =]*'.$allowattributes.'=("[^"]*"|\'[^\']*\')/i", "", $matches[0]);'
),$string);
}
return $string;
}
?>
Knowledge keywords: