Display the number of comments for the current post outside the loop:
<?php
global $wpdb, $table_prefix, $wp_query;
$post_id = $wp_query->post->ID;
$num_comments = $wpdb->get_var("
SELECT COUNT(1) FROM {$table_prefix}comments
WHERE comment_post_ID = " . $post_id . "
AND comment_approved = '1'
");
echo $num_comments;
?>
There is probably a more efficient way to do this, but it works 🙂
(This only works on single post pages obviously)
I put your code into my sidebar2.php and replaced the non-working code and its work great now.
THANK YOU!
Aleister,
Thank you so much!
I crawled nearly the whole net to find a solution on how to check and display the number of comments outside the loop!
(@j5onfield)
17 years ago
I’ve read over the topics on comments_number but i cant figure out why my post number is always “There’s zero responses for this post” when i do have posts.
If you can help take a look…
http://www.teamxmods.com/doityourself-blaster360-cheapmod/
You can see on the right that its not showing the correct amount of posts?
————————————
My sidebar2.php
<div id=”sidebarpostdata”>
Posted on <?php the_time(‘F jS, Y’) ?> at <?php the_time(‘g:i a’); ?> by <?php the_author() ?> in <?php the_category(‘, ‘) ?>. There’s <?php comments_number(‘zero responses’,’one response’,’% responses’); ?> for this post.
</div>
—————————————-
My Comments.php
<h2 id=”comments”><?php comments_number(__(‘Zero Comments’), __(‘1 Comment’), __(‘% Comments’)); ?>
<?php if ( comments_open() ) : ?>
“>»
<?php endif; ?>
</h2>
——————————————
My Single.php
<?php
comments_popup_link(‘No Comments »’, ‘1 Comment »’, ‘% Comments »’); ?></p><div class=”divider”></div></div>
</div>
<?php comments_template(); ?>
——————————————-
Thanks,
Jason