WordPress to get the number of comments of the current article

Time:2019-12-2

Sometimes, in order to get the number of comments of the current article of WordPress, you must know the ID of the current article to get the number of comments. How to get the ID of the current article and the number of comments?
For example, loop through articles of a certain category:

Copy code

The code is as follows:

<?php $posts = get_posts( “category=9&numberposts=5” ); ?>
<?php if( $posts ) : ?>
<?php foreach( $posts as $post ) : setup_postdata( $post ); ?>
<?php $id=$post->ID; echo get_post($id)->comment_count;?>
<?php endforeach; ?>
<?php endif; ?>

As shown in the red part above, get the ID of the current article through $post – > ID, and then get post ($ID) – > comment_count to get the number of comments of the current article.