Make WordPress Core

Ticket #19901: union_count_comments.php

File union_count_comments.php, 1.5 KB (added by ComputerGuru, 11 years ago)

Using UNION to update comment counts

Line 
1<?php
2
3function custom_tweak_wp_count_comments( $post_id = 0 ) {
4 global $wpdb;
5
6 $args = func_get_args();
7 $post_id = $args[1];
8
9 $post_id = (int) $post_id;
10
11 $count = wp_cache_get("comments-{$post_id}", 'counts');
12
13 if ( false !== $count )
14 return $count;
15
16
17 $where = 'WHERE';
18 if ( $post_id > 0 )
19 $where .= $wpdb->prepare( " comment_post_ID = %d AND", $post_id );
20
21 $query = "(SELECT COUNT( comment_ID ) FROM {$wpdb->comments} {$where} comment_approved = 'trash') UNION ALL
22(SELECT COUNT( comment_ID ) FROM {$wpdb->comments} {$where} comment_approved = 'spam') UNION ALL
23(SELECT COUNT( comment_ID ) FROM {$wpdb->comments} {$where} comment_approved = '0') UNION ALL
24(SELECT COUNT( comment_ID ) FROM {$wpdb->comments} {$where} comment_approved = 'post-trash') UNION ALL
25(SELECT COUNT( comment_ID ) FROM {$wpdb->comments});";
26
27 $counts = $wpdb->get_col($query);
28
29 $trash = $counts[0];
30 $spam = $counts[1];
31 $unapproved = $counts[2];
32 $post_trash = $counts[3];
33 $all = $counts[4];
34
35 $approved = $all - $unapproved - $spam - $trash - $post_trash;
36
37 $stats = array(
38 'approved' => $approved,
39 'moderated' => $unapproved,
40 'spam' => $spam,
41 'trash' => $trash,
42 'post-trashed' => $post_trash,
43 'total_comments' => $spam + $approved + $unapproved,
44 'all' => $approved + $unapproved,
45 );
46
47 $stats = (object) $stats;
48 wp_cache_set("comments-{$post_id}", $stats, 'counts');
49
50 return $stats;
51}
52add_filter('wp_count_comments', 'custom_tweak_wp_count_comments', 10, 2 );
53
54?>