4

I need to print comments belonging to a given node. So basically, get a node id then choose all the comments from a given node and print them. I know that I can print one comment (for example with id=12) using the following code:

<?php
$comment = _comment_load(12);
return theme('comment',$comment);
?>

Can anyone tell me how to do this?

6

If you are looking for a ready to use function, take a look at comment_render().

Example use (say the node you want comments for has nid = 5):

<?php
  $node = node_load(5);
 print comment_render($node);
?>

Or else you can manually query the database (comments table) to get all comments that have a matching nid.

<?php
  $nid = 5;
  db_query('SELECT * FROM {comments} WHERE nid = %d', $nid);
?>
| improve this answer | |
  • not a drupal 7 valid, for information – khaled_webdev Jun 11 '15 at 18:42
3

If you like to load the complete comment objects you can use this:

$result = db_select('comment')
  ->fields('comment', array('cid'))
  ->condition('nid', $node->nid, '=')
  ->execute();

$cids = $result->fetchCol();
$comments=comment_load_multiple($cids);

foreach($comments as $comment) {
  //do some stuff with the comment
  print $comment->comment_body ["und"][0] ["value"];
}
| improve this answer | |
  • Please use the formatting options as explained above the answer form. It makes your answer better readable and thus provides for a better exchange of information. – berliner Jan 28 '14 at 22:41
1

In Drupal 7 and onwards comment_render has been removed. Instead, you can load comments like this.

$result = db_select('comment')
                  ->fields('comment', array('name','subject'))
                  ->condition('nid', $node->nid, '=')
                  ->execute()
                  ->fetchAssoc();
foreach($result as $comment) {
   print $comment;
 }
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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