I'm creating a new node using hook_cron(). It all works except the node author is always set as anonymous (uid = 0). How can I assign a user to the new node, with say uid 21 for example?

Below is the node creation code that I have in a function that gets called within hook_cron().

<?php
$node = new stdClass();
$node->type = $type;
$node->title = "Some node title";
$node->language = LANGUAGE_NONE;
$node->uid = 21;
node_object_prepare($node);

$node->body[$node->language][0]['value'] = '';
$node->body[$node->language][0]['summary'] = '';
$node->body[$node->language][0]['format'] = 'html_text';

$node->field_quote[$node->language][0]['value'] = $some_value;
$node->field_quote[$node->language][0]['format'] = 'plain_text';

$node = node_submit($node);
node_save($node);
?>

Even though I state $node->uid = 21;, it always results in an anonymous author.

Comments

Drave Robber’s picture

If $node->name is not set or doesn't correspond to an existing user, node_submit() would set $node->uid to 0. Hence, you need to either:

  • set $node->name, or
  • skip node_submit(), as it doesn't do much these days anyway. (in D6, it populated teasers and such, but not in D7)
tce’s picture

Spot on. Thanks!