WordPress: RETURN comment count

May 25, 2004
6:38 am
Posted in: General, Tech, WordPress

One of the very few gripes I have with WordPress is that some functions ECHO a variable, and others RETURN it. The naming system is all over the place, so you can’t look at a function and say “get_comment_count(); must return the value, and show_comment_count(); must display it!” I wanted to perform some logic on my entries with the comment count. WordPress has a function to echo the count, and you can pass strings to it such as “no comments” and “1 comment” and “% comments” so it displays correctly, but the result is echoed.

Of course, my favorite thing about WordPress is the really really REALLY simple plugin system. I looked at the function that echoes the comment count (comments_number();), changed it to do what I wanted, called the function “get_comments_count();” and saved it as a PHP file in my plugins directory. One quick trip into WordPress to activate the plugin, and I was in business.

Here’s the plugin:

<?php
/*
Plugin Name: Get Comments Count
Version: 1.0
Plugin URI: http://txfx.net/
Description: Returns (not displays!) the current number of comments.  Use it in "the loop."
Author: Mark Jaquith
Author URI: http://txfx.net/
*/

function get_comments_count() {
global $id, $comment, $tablecomments, $wpdb, $comment_count_cache;
if ('' == $comment_count_cache["$id"]) $number = $wpdb->get_var("SELECT COUNT(*) FROM $tablecomments WHERE comment_post_ID = $id AND comment_approved = '1'");
else $number = $comment_count_cache["$id"];
return $number;
}
?>

And a final thought on the subject:

if($wordpress_function_naming_system == 'dodgy') {
blame_photomatt(); // Just kidding!  ;-) 
}
Mark Jaquith

Hi. I’m Mark Jaquith (JAKE-with). I make the WordPress publishing platform and am a freelance WordPress consultant. This is my personal blog. You can subscribe to my feed or follow me on Twitter and Google+.

7 Responses

Comments temporarily hidden. Will unhide once I get the spam under control.