Getting count of comments after filtered query?
-
Hi,
In a custom plugin, I’m excluding some comments from display with the following code:
add_action( 'pre_get_comments', 'action_pre_get_comments', 10, 1 ); function action_pre_get_comments( &$WP_Comment_Query ) { $excluded_uids = array( 1, 2, 3 ); // For example. $WP_Comment_Query->query_vars['author__not_in'] = $excluded_uids; }
This returns only the comments I’m after, so this part seems good. The issue I’m having is that the get_comments_number() function used in themes still returns the total number of comments for the post, rather than the number of filtered/returned comments. So, for example, if a post has 10 replies and I’m excluding 5 of them from display, the get_comments_number() is still reporting 10 replies even though only the 5 are displayed. I’d like to fix this.
I found that I can get the expected number (total comments minus excluded comments) with this:
add_filter( 'comments_array', 'filter_comments_array', 10, 2 ); function filter_comments_array( $comments_flat, $post_id ) { $total_comments_minus_excluded = count( $comments_flat ); }
I’d like to avoid editing the (child) theme’s comments.php file, if possible, but I’m not sure what to try next. Is this along the lines of the right approach? Or will I have to create a new function and edit the comments.php file in the theme?
Thank you for your help.
Teck
- The topic ‘Getting count of comments after filtered query?’ is closed to new replies.