views:

9

answers:

1

I need to build and print a deeplink to any given comment. So that the user can directly access the specific comment with just clicking a link. I could not find a native drupal function to get this so i build it my own.

My solution

<?php
    global $base_url;
    $base = drupal_lookup_path('alias',"node/".$node->nid);
    $path = $base_url.'/'.$base.'#comment-'.$comment->cid;

    $link_options = array('html'=> $html);
    $commentlink = l($date, $path, $link_options);
?>

To print the link you only have to call <?php print $commentlink;?>. But i'm pretty sure there is better and much more drupal like way to solve the problem.

The Better Way

Mikeker did it :) As he suggested here are the solution.

<?php
 $commentlink = l(
    $date,
    "node/$comment->nid",
    array("fragment" => "comment-$comment->cid"));
?>

Note the little difference bettween Mikeker and my version. array("fragment" => "comment-$comment->cid")); and array("query" => "comment-$comment->cid"));

The query param will add an ? to the url. So your path looks like

//…query
http://example.com/path/to/node?comment-2

In opposite to my solution (fragment):

//…fragment
http://example.com/path/to/node#comment-2

Note: Do not include the leading '#' character to a fragment identifier. It will be added by drupal.

A: 

That's basically the way to do it. Comment permalinks are in the form of:

node/<nid>#comment-<cid>

Where <nid> and <cid> are the node and comment IDs, respectively. You can save yourself a step by not doing calling drupal_lookup_path() -- l() or url() do it for you. The shortened routine would look like:

$commentlink = l(
  $date,                                      // Text of the link
  "node/$node->nid",                          // path to node, l() handles aliases
  array('query' => "comment/$comment->cid"),  // fragment to specific comment
);
mikeker
Thank you very much mikeker :)
gearsdigital