I have some nodes with lots of comments that use a pager. I want to link from the top of the node page to the last comment.

Is there a simpler way than building the link like this (source):

  1. Get number of (published) comments for a certain node;
  2. Get number of comments per page (it can differ from on content type to another);
  3. 1+2 = number of pages;
  4. Get cid of the last comment;
  5. Create a link like /node/[nid]?page=[page]#comment-[cid]

1 Answer 1


I don't think there's a simpler way than that, but you can combine two of those steps into one so you at least only need to make a single database call:

function node_last_comment_link($node, $link_text) {
  // Get the num active comments and most recent comment id
  $data = db_query('SELECT MAX(cid) AS cid, COUNT(cid) AS cnt FROM {comment} WHERE nid = :nid AND status = 1', array(':nid' => $node->nid))->fetchObject();

  // No comments, no link
  if ($data->cnt == 0) {
    return FALSE;

  // Get the num comments per page
  $var_name = 'comment_default_per_page_' . $node->type;
  $sensible_default = 50;
  $num_per_page = variable_get($var_name, $sensible_default);
  $page_num = floor($data->cnt / $num_per_page);

  //Build and return a URL
  $query = array();

  // No point adding ?page=0
  if ($page_num > 0) {
    $query['page'] = $page_num;

  $fragment = 'comment-' . $data->cid;
  return l($link_text, 'node/' . $node->nid, array('query' => $query, 'fragment' => $fragment));

I've given that a quick test and it seems to work but it might need a bit of massaging, especially if you have threading turned on :)

  • I ended up adding a 2nd pager to the top: drupal.org/node/141381#comment-4984614
    – uwe
    Commented Apr 6, 2012 at 1:15
  • @Clive, nice answer, thanks. But what if we have tree view in comments. E.g. we have 5 pages with comments and somebody replies on comment on the second page. CID will be the lastest but how can we detect $page_num? In this case we need to detect all comment parents maybe..
    – milkovsky
    Commented Jul 23, 2013 at 8:59
  • So I think better would be to use comment_get_display_page()
    – milkovsky
    Commented Jul 23, 2013 at 9:56
  • @milkovsky Yeah I think you're right :)
    – Clive
    Commented Jul 23, 2013 at 11:28

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