Using WordPress ‘comments_popup_link()’ PHP function

The comments_popup_link() WordPress PHP function displays a link to the comments for the current post ID. It provides different strings for different comment situations – no comments, one comment, multiple comments, and when comments have been turned off.

Usage

Here’s a simple way to use comments_popup_link(). It will display different messages depending on the number of comments.

comments_popup_link('Be the first to comment', 'One comment so far', '% comments already');

Parameters

  • $zero false|string Optional. String to display when no comments. Default: false
  • $one false|string Optional. String to display when only one comment is available. Default: false
  • $more false|string Optional. String to display when there are more than one comment. Default: false
  • $css_class string Optional. CSS class to use for comments. Default: ”
  • $none false|string Optional. String to display when comments have been turned off. Default: false

More information

See WordPress Developer Resources: comments_popup_link()

Examples

Load Different CSS classes according to Comment-condition

$css_class = 'zero-comments';
$number = (int) get_comments_number(get_the_ID());
if (1 === $number) {
    $css_class = 'one-comment';
} elseif (1 < $number) {
    $css_class = 'multiple-comments';
}
comments_popup_link('Post a Comment', '1 Comment', '% Comments', $css_class, 'Comments are Closed');

This code will add different CSS classes based on the number of comments.

Text Response for Number of Comments with Localization

comments_popup_link(__('Leave a comment', 'text-domain'), __('1 Comment', 'text-domain'), __('% Comments', 'text-domain'));

This code uses localization to display the comment link. It’s useful for sites in multiple languages.

Text Response for Number of Comments

echo '<p>';
comments_popup_link('No comments yet', '1 comment', '% comments', 'comments-link', 'Comments are off for this post');
echo '</p>';

This code wraps the comment link in a <p> tag for additional styling.

if (comments_open()) {
    echo '<p>';
    comments_popup_link('No comments yet', '1 comment', '% comments', 'comments-link', 'Comments are off for this post');
    echo '</p>';
}

This code checks if comments are open. If they are, it displays the comment link. If not, it hides the link.

Display Comment Count with Custom Messages

comments_popup_link('Start the conversation', 'Join the conversation', 'Join % others in the conversation');

This code displays custom messages encouraging users to comment. The % is replaced with the number of comments.