Using WordPress ‘comment_link()’ PHP function

The comment_link() WordPress PHP function is used to display the link to the comments.

Usage

Here’s an example of how you could use this function to display a link to a comment in your WordPress theme:

<a href="<?php comment_link(); ?>">Permalink to this comment</a>

This will output something like:

<a href="http://example.com/2009/07/15/example-post/comment-page-1/#comment-3">Permalink to this comment</a>

Parameters

  • $comment int|WP_Comment Optional: This parameter allows you to specify a Comment object or ID. If not provided, it defaults to the global comment object. Default value is null.

More information

See WordPress Developer Resources: comment_link()
This function is part of the WordPress core and can be found in the wp-includes/comment-template.php file.

Examples

This code will display a permalink to a specific comment:

// Fetch a specific comment by ID
$comment = get_comment($comment_id);

// Display the comment link
echo '<a href="' . comment_link($comment) . '">Permalink to this comment</a>';

Using within The Loop

This code snippet shows how to use comment_link() within The Loop:

// Start The Loop
while (have_posts()) : the_post();

    // Display comment links for each post
    comments_popup_link('No Comments', '1 Comment', '% Comments');

endwhile;

This example demonstrates how to display comment links in a list of comments:

// Fetch all comments for a post
$comments = get_comments(array('post_id' => $post->ID));

// Loop through each comment
foreach($comments as $comment) {
    // Display the comment link
    echo '<a href="' . comment_link($comment) . '">Permalink to this comment</a>';
}

This example shows how to display a comment link with custom text:

// Fetch a specific comment by ID
$comment = get_comment($comment_id);

// Display the comment link with custom text
echo '<a href="' . comment_link($comment) . '">Go to this comment</a>';

This example demonstrates how to display a comment link with the author’s name:

// Fetch a specific comment by ID
$comment = get_comment($comment_id);

// Display the comment link with the author's name
echo '<a href="' . comment_link($comment) . '">View comment by ' . $comment->comment_author . '</a>';