Make WordPress Core


Ignore:
Timestamp:
05/01/2008 04:52:48 PM (16 years ago)
Author:
ryan
Message:

Add per post counting to wp_count_comments(). Props josephscott. fixes #6884

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/wp-includes/comment.php

    r7714 r7868  
    449449}
    450450
    451 function wp_count_comments() {
     451function wp_count_comments( $post_id = 0 ) {
    452452    global $wpdb;
    453453
    454     $count = wp_cache_get('comments', 'counts');
     454    $post_id = (int) $post_id;
     455
     456    $count = wp_cache_get('comments', "counts-{$post_id}");
    455457
    456458    if ( false !== $count )
    457459        return $count;
    458460
    459     $count = $wpdb->get_results( "SELECT comment_approved, COUNT( * ) AS num_comments FROM {$wpdb->comments} GROUP BY comment_approved", ARRAY_A );
    460 
     461    $where = '';
     462    if( $post_id > 0 )
     463        $where = $wpdb->prepare( "WHERE comment_post_ID = %d", $post_id );
     464
     465    $count = $wpdb->get_results( "SELECT comment_approved, COUNT( * ) AS num_comments FROM {$wpdb->comments} {$where} GROUP BY comment_approved", ARRAY_A );
     466
     467    $total = 0;
    461468    $stats = array( );
    462469    $approved = array('0' => 'moderated', '1' => 'approved', 'spam' => 'spam');
    463470    foreach( (array) $count as $row_num => $row ) {
     471        $total += $row['num_comments'];
    464472        $stats[$approved[$row['comment_approved']]] = $row['num_comments'];
    465473    }
    466474
     475    $stats['total_comments'] = $total;
    467476    foreach ( $approved as $key ) {
    468477        if ( empty($stats[$key]) )
     
    471480
    472481    $stats = (object) $stats;
    473     wp_cache_set('comments', $stats, 'counts');
     482    wp_cache_set('comments', $stats, "counts-{$post_id}");
    474483
    475484    return $stats;
Note: See TracChangeset for help on using the changeset viewer.