2

How can I show the amount of a comment per post outside the loop? I tried this in a function already:

' . get_comments_number . ' , but that outputted the text "array" on the screen... What do I have to do for getting it to work?

On my single.php I used this to output some list items (posts):

<ul class="wow dude">
<?php echo wowPosts(2); ?>
</ul>

And in my functions.php I used this:

function wowPosts($num) {
    global $wpdb;

    $posts = $wpdb->get_results("SELECT comment_count, ID, post_title FROM $wpdb->posts ORDER BY comment_count DESC LIMIT 0 , $num");

    foreach ($posts as $post) {
        setup_postdata($post);
        $id = $post->ID;
        $title = $post->post_title;
        $count = $post->comment_count;
        $comment_count = get_comment_count($post->ID);
        $all_comments = get_comment_count( array ( 'post_id' => get_the_ID() ) );

        if ($count != 0) {
            $popular .= '<li>';
            $popular .= '<a href="' . get_permalink($id) . '" title="' . $title . '">' . $title . '</a> '. count( $all_comments ) . ' ';
            $popular .= '</li>';
        }
    }
    return $popular;
}

As you can see, I have edited your first code and implemented in this function so that I can use it per list item (per post)... It still shows a 4 everywhere.

4

To print just the total number of comments for a given post ID, use the count argument:

echo get_comments(
    array (
        // post ID
        'post_id' => 149,
        // return just the total number
        'count'   => TRUE
    )
);

or just use

// Argument: Post ID
echo get_comment_count( 149 );

To get the total number of all comments of all posts on the current page, you can use the comment_count property of the post objects and sum them up:

echo array_sum(
    wp_list_pluck( $GLOBALS['wp_query']->posts, 'comment_count' )
);
6
  • If I put this code in functions.php, than what? Wouldn't that show only one posts comment and not from all the posts in a list? – user1627363 May 13 '13 at 13:57
  • @user1627363 Oh, that changes your question a little bit. :) See my update to get the sum of all comments for a page. – fuxia May 13 '13 at 14:05
  • Nope my brother, not working either... Shows a zero... See my edit on the first post to give a better look at what I want. Maybe that will help it out... – user1627363 May 13 '13 at 14:10
  • I tested this code too. It will fail only in cases where the main query was overwritten with query_posts() or similar legacy code. – fuxia May 13 '13 at 14:12
  • I am using a function (see first post). The query_post is beneath that, but isn't used for what I want (yet). Still not working... I know that I do something wrong, but what... – user1627363 May 13 '13 at 14:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.