have_comments()WP 2.2.0

Whether there are comments to loop over.

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.

Return

true|false. True if comments are available, false if no more comments.

Usage

have_comments();

Examples

0

#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.4.3

function have_comments() {
	global $wp_query;

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

	return $wp_query->have_comments();
}