Code Sweep: A Simple Approach to a Neater WordPress User List

Feel like clearing out your spam users? With the snippet below we can make your job much easier!

/**
 * Adds a new column to the user management screen for displaying the number of comments.
 *
 * @param array $columns The existing columns in the user management screen.
 *
 * @return array The modified columns array with the new 'comments_count' column added.
 */
function emrikol_add_comments_column( array $columns ): array {
	$columns['comments_count'] = esc_html__( text: 'Comments', domain: 'default' );
	return $columns;
}
add_filter( 'manage_users_columns', 'emrikol_add_comments_column' );

/**
 * Displays the number of comments for a user in the custom column.
 *
 * @param string $output       The value to be displayed in the column.
 * @param string $column_name  The name of the custom column.
 * @param int    $user_id      The ID of the user.
 *
 * @return string              The updated value to be displayed in the column.
 */
function emrikol_show_comments_count( string $output, string $column_name, int $user_id ): string {
	if ( 'comments_count' == $column_name ) {
		$args           = array(
			'user_id' => $user_id,
			'count'   => true,
		);
		$comments_count = get_comments( args: $args );
		return number_format_i18n( number: $comments_count );
	}

	return $output;
}
add_action( 'manage_users_custom_column', 'emrikol_show_comments_count', 10, 3 );
Code language: PHP (php)

This will add a “Comments” count to the WordPress user list so you can easily determine which users you can delete:

What a sad state this blarg is in…

Other Posts Not Worth Reading

Hey, You!

Like this kind of garbage? Subscribe for more! I post like once a month or so, unless I found something interesting to write about.


Comments

Leave a Reply