Programmatically create Drupal 7 comment with redirect.

Public

This is the basic of posting your comment programmatically.

</> CopyGet raw version
php
  1. $comment_subject = $_POST['comment_title']; // Get the comment subject.
  2. $comment_body = $_POST['comment_body']; // Get the comment body.
  3. $comment_field_xyz = $_POST['comment_field_xyz']; // Get the custome field if you have one.
  4.  
  5. global $user;
  6. $user = user_load($user->uid);
  7.  
  8. $node = node_load($nid); // The node being commented on.
  9.  
  10. $comment = new stdClass();
  11.  
  12. $comment->nid = $node->nid; // nid of a node you want to attach a comment to
  13. $comment->cid = 0; // leave it as is
  14. $comment->pid = 0; // parent comment id, 0 if none
  15. $comment->uid = $user->uid; // user's id, who left the comment
  16. $comment->mail = $user->mail; // user's email
  17. $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
  18. $comment->thread = '01/'; // OPTIONAL. If you need comments to be threaded you can fill this value. Otherwise omit it.
  19. $comment->hostname = '127.0.01' // OPTIONAL. You can log poster's ip here
  20. $comment->created = time(); // OPTIONAL. You can set any time you want here. Useful for backdated comments creation.
  21. $comment->is_anonymous = 0; // leave it as is
  22. $comment->homepage = ''; // you can add homepage URL here
  23. $comment->status = COMMENT_PUBLISHED; // We auto-publish this comment
  24. $comment->language = LANGUAGE_NONE; // The same as for a node
  25. $comment->subject = $comment_subject;
  26. $comment->comment_body[$comment->language][0]['value'] = $comment_body; // Everything here is pretty much like with a node
  27. $comment->comment_body[$comment->language][0]['format'] = 'filtered_html';
  28. $comment->field_custom_field_name[LANGUAGE_NONE][0]['value'] = comment_field_xyz; // OPTIONAL. If your comment has a custom field attached it can added as simple as this // preparing a comment for a save
  29.  
  30. comment_submit($comment); // saving a comment
  31. comment_save($comment);
  32.  
  33. $destination = 'node/' . $node->nid;
  34. drupal_goto($destination);