Using WordPress ‘comments_link()’ PHP function

The comments_link() WordPress PHP function displays the link to the current post comments.

Usage

To use the comments_link() function, you simply need to place it where you want the comment link to appear. For instance, within an HTML anchor tag:

<a href="<?php comments_link(); ?>">Comments</a>

This will output a link to the comments of the current post.

Parameters

  • $deprecated (string): This parameter is optional and not used. Default is an empty string.
  • $deprecated_2 (string): This parameter is also optional and not used. Default is an empty string.

More information

See WordPress Developer Resources: comments_link()

The comments_link() function has been in use since the earlier versions of WordPress, and there’s currently no information about its deprecation. It’s important to note that the output of comments_link() is already escaped by core.

Examples

Basic usage

This is the simplest way to use the function. It displays a link to the comments of the current post.

<a href="<?php comments_link(); ?>">Comments</a>

Usage within a loop

If you want to display comment links for multiple posts, you can use the function within a WordPress loop.

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
  <a href="<?php comments_link(); ?>">Comments for <?php the_title(); ?></a>
<?php endwhile; endif; ?>

Usage with conditional statement

This example uses comments_link() within a conditional statement to only display the link if comments are open for the post.

<?php if ( comments_open() ) : ?>
  <a href="<?php comments_link(); ?>">Comments</a>
<?php endif; ?>

Usage with comment count

This example displays a link to the comments along with the number of comments on the post.

<a href="<?php comments_link(); ?>">Comments (<?php comments_number('0', '1', '%'); ?>)</a>

Usage with custom text

This example shows how to use the function with custom link text, depending on the number of comments.

<a href="<?php comments_link(); ?>">
  <?php comments_number('Be the first to comment', 'One comment', '% comments'); ?>
</a>