Add Snippet To Project
If you run a blog or website and have enabled comments, you may want to know the total number of comments that have been made on your site. Whether you’re curious about how active your comment section is or want to keep track of engagement, WordPress makes it easy to display the total number of comments on your site. In this article, we’ll show you several ways to display the total number of comments in WordPress.
function wpturbo_total_number_of_comments() {
global $wpdb;
$count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = '1'" );
return $count;
}
The code snippet defines a new function wpturbo_total_number_of_comments(). This function retrieves and returns the total number of approved comments in the WordPress database.
We use the global $wpdb variable to access the WordPress database. Then, we use the $wpdb->get_var() method to query the database and retrieve the count of approved comments.
The SQL query used is "SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = ‘1’". This query selects the number of rows in the comments database table where the comment_approved field is equal to 1. This ensures that we only count approved comments and not spam or unapproved ones.
Finally, we return the count value, which can be used by other functions or templates.
To use this function, you can call it in your WordPress template files or functions.php file by using echo wpturbo_total_number_of_comments();. This will output the total number of approved comments on your website.
