Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.