2

I want to print a individual comment in drupal based on it's comment ID. How can I do this? Google and other sources have yielded me nothing. Thank you.

apaderno
  • 28,547
  • 16
  • 75
  • 90
alan
  • 391
  • 1
  • 4
  • 8
  • What is the context of this? Do you want to have a page that's just a comment? A block? Make it part of a page template? Print a single comment in a node template? – Sean McSomething Mar 23 '09 at 20:52

3 Answers3

3
function print_comment($cid) {
  $sql = "SELECT * FROM {comments} WHERE cid = %d";
  if ($comment = db_fetch_object(db_query($sql, $cid))) {
    $node = node_load($comment->nid);
    return theme('comment', $comment, $node);
  }
}
Eaton
  • 7,405
  • 2
  • 26
  • 24
3

Eaton's suggestion is good (except it's {comments}, not {comment}) if you need to display the comment like core does it, including the info coming from the node. Except the default theme_comment implementation in modules/comment/comment.tpl.php makes no use of $node.

However, I'd do it slightly differently, because if you need to extract a single comment, displaying it with the normal content formatting provided by comment.tpl.php is likely to be inappropriate.

function print_comment($cid) {
  $sql = "SELECT * FROM {comment} c WHERE c.cid = %d";
  if ($comment = db_fetch_object(db_rewrite_sql(db_query($sql, $cid), 'c'))) {
    return theme('my_special_comment_formatting', $comment);
  }
}

And of course, define this special commment formatting in your module's hook_theme() implementation, inspired by what comment.tpl.php does.

2014-02 UPDATE: note that this is a 2009 question/answer. In Drupal 8, you just don't want to access the hypothetical underlying SQL database (and would not do it like this anyway, but use DBTNG), but just use something like:

if ($comment = entity_load('comment', $cid)) {
  return entity_view($comment, $view_mode);
}
FGM
  • 2,830
  • 1
  • 31
  • 31
  • Hah. Thanks for noting the comment/comments distinction. I'd popped open api.drupal.org and not noticed I was looking at the D7 version of the code -- the table name has changed to singular in the new dev release. – Eaton Mar 21 '09 at 16:56
  • Also, you'll get some PHP notices if there isn't a node object passed in -- $node->type is used to construct possible template options (like comment-story.tpl.php) in the default phptemplate\_preprocess\_comment function. – Eaton Mar 21 '09 at 16:57
  • `phptemplate_preprocess_comment` won't be used when invoking theme('my_special_comment_formatting'), though. But good catch for `theme('comment')` ! I had only checked the template, not the preprocess function. – FGM Mar 21 '09 at 20:25
2

No reason to use any sql to do this, two drupal api function calls is all it takes.

function print_comment($cid) 
{
    $comment = _comment_load($cid);
    return theme('comment',$comment);
}
TrippRitter
  • 305
  • 2
  • 10