I've made my own module to add commenting to a node (it opens modally in a colorbox - really nice). The form works great, but how do I save the comment?

I know it's got to be done using comment_save. But, as usual, drupal.org is great at showing the code for the function without giving an example...

Has anyone done this before?

I'm guessing it's something like:

$comment = new stdClass();

$comment->nid = $the_node_the_comment_is_for;
$comment->title = $my_comment_title;
$comment->body = $my_comment_body;


Yes you can save comment dynamically using comment_save() function, a working example is given below


$comment = new stdClass();

$comment->nid = 28; // nid of a node you want to attach a comment to
$comment->cid = 0; // leave it as is
$comment->pid = 0; // parent comment id, 0 if none 
$comment->uid = 1; // user's id, who left the comment
$comment->mail = 'email@example.com'; // user's email
$comment->name = 'User name'; // If user is authenticated you can omit this field, it will be auto-populated, if the user is anonymous and you want to name him somehow, input his name here
$comment->thread = '01/'; // OPTIONAL. If you need comments to be threaded you can fill this value. Otherwise omit it.
$comment->hostname = '127.0.01' ;// OPTIONAL. You can log poster's ip here
$comment->created = time(); // OPTIONAL. You can set any time you want here. Useful for backdated comments creation.
$comment->is_anonymous = 0; // leave it as is
$comment->homepage = ''; // you can add homepage URL here
$comment->status = COMMENT_PUBLISHED; // We auto-publish this comment
$comment->language = LANGUAGE_NONE; // The same as for a node
$comment->subject = 'Comment subject'; 
$comment->comment_body[$comment->language][0]['value'] = 'Comment body text'; // Everything here is pretty much like with a node
$comment->comment_body[$comment->language][0]['format'] = 'filtered_html'; 
$comment->field_custom_field_name[LANGUAGE_NONE][0]['value'] = 'Some value'; // OPTIONAL. If your comment has a custom field attached it can added as simple as this // preparing a comment for a save

comment_submit($comment); // saving a comment

protected by Community Jul 3 '18 at 4:09

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.