Using WordPress ‘get_comments_link()’ PHP function

The get_comments_link() WordPress PHP function retrieves the link to the current post’s comments.

Usage

get_comments_link( $post )

Custom Example:

Input:

$post_id = 42;
echo get_comments_link( $post_id );

Output:

https://example.com/post-slug/#comments

Parameters

  • $post (int|WP_Post) (Optional) – Post ID or WP_Post object. Default is the global $post object.

More information

See WordPress Developer Resources: get_comments_link()

Examples

Display comments link for the current post

This example retrieves the comments link for the current post and displays it.

// Get comments link for the current post
$comments_link = get_comments_link();
echo "Read and leave comments at: " . $comments_link;

This example retrieves the comments link for the current post and displays it with custom text.

// Get comments link for the current post
$comments_link = get_comments_link();
echo "<a href='" . $comments_link . "'>Join the discussion</a>";

Display comments link for a specific post

This example retrieves the comments link for a specific post with ID 42 and displays it.

// Get comments link for post with ID 42
$post_id = 42;
$comments_link = get_comments_link( $post_id );
echo "Visit the comments section at: " . $comments_link;

Display comments link for a WP_Post object

This example retrieves the comments link for a WP_Post object and displays it.

// Get a WP_Post object
$post_obj = get_post( 42 );

// Get comments link for the WP_Post object
$comments_link = get_comments_link( $post_obj );
echo "Check out the comments at: " . $comments_link;

This example retrieves the comments link for the current post and displays it with the number of comments.

// Get comments link and count for the current post
$comments_link = get_comments_link();
$comments_count = get_comments_number();

echo "There are " . $comments_count . " comments. <a href='" . $comments_link . "'>Read them here</a>";