Include comment count and link to comments

Display Posts includes many Display Parameters for customizing what is shown for each post in the list.

It does not include an option for listing the comment count, but you can add one yourself using the Output Filter.

Once the code below has been added to your site, you can include the comments link like so:

Shortcode

[display-posts include_comments_link="true"]

It will say “No Comments” if there are none, “1 Comment” if there is one, and “X Comments” if there are more than one. You can customize this text in the “Build the comment link” section below. The comment count will be a link that takes you directly to the comment section of your post.

You can customize where the comments link appears by moving $comments_link in the final $output line. I currently have it displaying after the author (if you have include_author="true") and before the category listing (if you have category_display="true").

This code snippet goes in a core functionality plugin or Code Snippets.

/**
 * Display Posts, include_comments_link parameter
 * @see https://displayposts.com/2019/02/20/include-comment-count-and-link-to-comments/
 *
 */
function be_dps_include_comments_link( $output, $original_atts, $image, $title, $date, $excerpt, $inner_wrapper, $content, $class, $author, $category_display_text ) {

	if( !empty( $original_atts['include_comments_link'] ) && true === filter_var( $original_atts['include_comments_link'], FILTER_VALIDATE_BOOLEAN ) ) {

		// Build the comment link
		$num_comments = get_comments_number();
		$comments_link = '';
		if ( comments_open() ) {
			if ( $num_comments == 0 ) {
				$comments = __( 'No Comments' );
			} elseif ( $num_comments > 1 ) {
				$comments = $num_comments . __( ' Comments' );
			} else {
				$comments = __( '1 Comment' );
			}
			$comments_link = ' <a class="comments-link" href="' . get_comments_link() . '">' . $comments . '</a> ';
		}

		// Place $comments_link where you'd like it to appear. I've added it after $author
		$output = '<' . $inner_wrapper . ' class="' . implode( ' ', $class ) . '">' . $image . $title . $date . $author . $comments_link . $category_display_text . $excerpt . $content . '</' . $inner_wrapper . '>';
	}

	return $output;
}
add_filter( 'display_posts_shortcode_output', 'be_dps_include_comments_link', 10, 11 );

Filters used:

Published by Bill Erickson

Bill Erickson is a freelance WordPress developer and a contributor to the Genesis framework. For the past 14 years he has worked with attorneys, publishers, corporations, and non-profits, building custom websites tailored to their needs and goals.