I believe the below should do the trick, just add to your functions.php
file.
/**
* Prevent non-administrator users from viewing others comments.
*/
add_filter( 'comments_list_table_query_args', function( $args ) {
global $pagenow;
if ( $pagenow == 'edit-comments.php' ) {
$user = wp_get_current_user();
$value = !empty( $args[ 'author__in' ] ) ? $args[ 'author__in' ] : [];
if ( is_array( $value ) && !in_array( $user->ID, $value ) && !in_array( 'administrator', (array)$user->roles ) ) {
$value[] = $user->ID;
}
$args[ 'author__in' ] = $value;
}
return $args;
}, PHP_INT_MAX );
I was able to put this together by viewing the code of wp-admin/edit-comments.php
. Within the file I found a call to the class WP_Comments_List_Table
(found in wp-admin/includes/class-wp-comments-list-table.php
) which extends the WP_List_Table
class.
From experience I knew the WP_List_Table
requires a method prepare_items()
which usually handles the query. In here I found the filter comments_list_table_query_args
which allows us to modify the query arguments before the comments query is made.