Comments Column in the Users List
Adds a "Comments" column to the Users screen showing how many approved comments each user has written, linked to their comments.
Opens WPIDE on
Code
$wpide_user_comment_counts = null;
add_filter( 'manage_users_columns', function ( $columns ) {
$columns['wpide_comments'] = 'Comments';
return $columns;
} );
add_filter( 'manage_users_custom_column', function ( $output, $column, $user_id ) use ( &$wpide_user_comment_counts ) {
global $wpdb, $wp_list_table;
if ( 'wpide_comments' !== $column ) {
return $output;
}
if ( null === $wpide_user_comment_counts ) {
$ids = isset( $wp_list_table->items ) ? array_map( 'intval', wp_list_pluck( (array) $wp_list_table->items, 'ID' ) ) : array();
$ids = array_filter( array_merge( $ids, array( (int) $user_id ) ) );
$rows = $wpdb->get_results( "SELECT user_id, COUNT(*) AS total FROM {$wpdb->comments} WHERE comment_approved = '1' AND user_id IN (" . implode( ',', $ids ) . ') GROUP BY user_id' );
$wpide_user_comment_counts = wp_list_pluck( (array) $rows, 'total', 'user_id' );
}
$count = (int) ( $wpide_user_comment_counts[ $user_id ] ?? 0 );
return $count ? '<a href="' . esc_url( admin_url( 'edit-comments.php?user_id=' . (int) $user_id ) ) . '">' . esc_html( number_format_i18n( $count ) ) . '</a>' : '0';
}, 10, 3 );
Notes
Counts for the whole page of users are fetched with one query.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.