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.

1 Answer
1

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' )
);

Leave a Reply

Your email address will not be published. Required fields are marked *