Search code examples
phpdrupal-6

Load comment variables in a block


In a drupal block, you can access the node variables by using node_load(arg(1)). But how do you get the comment variables in a block?


Solution

  • If you need to get the list of all the comments made for a node, you can use the following code:

    $query = 'SELECT c.nid, c.subject, c.cid, c.timestamp FROM {comments} c INNER JOIN {node} n ON n.nid = c.nid WHERE c.nid = %d AND n.status = 1 AND c.status = %d ORDER BY c.cid DESC';
    
    $result = db_query(arg(1), COMMENT_PUBLISHED);
    while ($comment = db_fetch_object($result)) {
      $comments[] = $comment;
    }
    

    Rather then just using arg(1), which would not consider the node revision in URLs like /node/<nid>/revision/<rid>, you should use menu_get_object(); in that case the code would become:

    $node = menu_get_object();
    if (!empty($node) && !empty($node->nid)) {
      $query = 'SELECT c.nid, c.subject, c.cid, c.timestamp FROM {comments} c INNER JOIN {node} n ON n.nid = c.nid WHERE c.nid = %d AND n.status = 1 AND c.status = %d ORDER BY c.cid DESC';
      $result = db_query($query, $node->nid, COMMENT_PUBLISHED);
      while ($comment = db_fetch_object($result)) {
        $comments[] = $comment;
      }
    }