have_comments()WP 2.2.0

Checks if there are comments to display on the current post page. Conditional tag.

Designed for use in the post page template, works based on the global variable $wp_query.

1 time — 0.000001 sec (speed of light) | 50000 times — 0.02 sec (speed of light) | PHP 7.1.5, WP 4.9.2

No Hooks.

Returns

true|false. true - there are comments to display. false - there are no comments to display.

Usage

if( have_comments() ){
	// there are comments, we display them
}

Examples

1

#1 Before displaying comments, Check if there are any comments

<?php
if( have_comments() ){

	// comments output 

	?>
	<ul class="commentlist">
		<?php 
		wp_list_comments( [ 
			'type'     => 'comment',
			'callback' => 'mytheme_comment',
		] );
		?>
	</ul>
	<?php
}
0

#2 Example based on Twentyten’s comments.php template

Comments title (and more) is displayed only when comments are available:

<?php 
if ( comments_open() ) {

	if ( have_comments() ) { 
		?>
		<h3 id="comments-title">
			<?php
			printf(
				_n( 'One Response to %2$s', '%1$s Responses to %2$s', get_comments_number(), 'twentyten' ),
				number_format_i18n( get_comments_number() ),
				'<em>' . get_the_title() . '</em>' 
			);
			?>
		</h3>

		// and more data...

		<?php
	}
	// or, if we don't have comments:
	else {

	}

}
// comments closed
else {
	?>
	<p class="nocomments"><?php _e( 'Comments are closed.', 'twentyten' ); ?></p>
	<?php 
}
?>

Notes

  • Global. WP_Query. $wp_query WordPress Query object.

Changelog

Since 2.2.0 Introduced.

have_comments() code WP 6.9

function have_comments() {
	global $wp_query;

	if ( ! isset( $wp_query ) ) {
		return false;
	}

	return $wp_query->have_comments();
}