WordPress.org

Make WordPress Core

Ticket #19901: 19901.diff

File 19901.diff, 2.2 KB (added by markjaquith, 4 years ago)
  • wp-includes/comment.php

    function wp_count_comments( $post_id = 0 ) { 
    914914        if ( false !== $count ) 
    915915                return $count; 
    916916 
    917         $where = ''; 
     917        $post_where = ''; 
    918918        if ( $post_id > 0 ) 
    919                 $where = $wpdb->prepare( "WHERE comment_post_ID = %d", $post_id ); 
    920  
    921         $count = $wpdb->get_results( "SELECT comment_approved, COUNT( * ) AS num_comments FROM {$wpdb->comments} {$where} GROUP BY comment_approved", ARRAY_A ); 
     919                $post_where = $wpdb->prepare( "comment_post_ID = %d", $post_id ); 
    922920 
    923         $total = 0; 
    924921        $approved = array('0' => 'moderated', '1' => 'approved', 'spam' => 'spam', 'trash' => 'trash', 'post-trashed' => 'post-trashed'); 
    925         foreach ( (array) $count as $row ) { 
    926                 // Don't count post-trashed toward totals 
    927                 if ( 'post-trashed' != $row['comment_approved'] && 'trash' != $row['comment_approved'] ) 
    928                         $total += $row['num_comments']; 
    929                 if ( isset( $approved[$row['comment_approved']] ) ) 
    930                         $stats[$approved[$row['comment_approved']]] = $row['num_comments']; 
    931         } 
    932922 
    933         $stats['total_comments'] = $total; 
    934         foreach ( $approved as $key ) { 
    935                 if ( empty($stats[$key]) ) 
    936                         $stats[$key] = 0; 
     923        foreach ( $approved as $status => $label ) { 
     924                if ( 'approved' == $label ) 
     925                        continue; // We'll infer this later 
     926                $status_where = $wpdb->prepare( "comment_approved = %s", $status ); 
     927                $where = "WHERE $status_where" . ( $post_where ? " AND $post_where" : '' ); 
     928                $stats[$label] = (int) $wpdb->get_var( "SELECT COUNT( comment_ID ) FROM {$wpdb->comments} {$where}" ); 
    937929        } 
     930        // Grab the total 
     931        $total_where = empty( $post_where ) ? '' : "WHERE $post_where"; 
     932        $stats['total_comments'] = (int) $wpdb->get_var( "SELECT count( comment_ID ) FROM {$wpdb->comments} {$total_where}" ); 
     933        $stats['total_comments'] = $stats['total_comments'] - $stats['post-trashed']; // Don't count post-trashed towards total 
     934 
     935        // Now, infer 'approved', by subtracting moderated, spam and trash from total_comments (post-trashed was already removed) 
     936        $stats['approved'] = $stats['total_comments'] - $stats['moderated'] - $stats['spam'] - $stats['trash']; 
    938937 
    939938        $stats = (object) $stats; 
    940939        wp_cache_set("comments-{$post_id}", $stats, 'counts');