Add Snippet To Project
If you’re a busy website owner or manager, it can be difficult to keep track of all the comments on your site. To make things easier, you may want to display comments on your admin dashboard for only the posts authored by your team of authors. In this article, we’ll show you how to do just that, using a simple code snippet that will help you save both time and energy. Let’s dive in and get started!
function wpturbo_filter_comments_by_author( $comments ) {
// Get the ID of the current author
$author_id = get_current_user_id();
// Loop through the comments and remove those that don't belong to the current author
foreach ( $comments as $key => $comment ) {
if ( $comment->user_id != $author_id ) {
unset( $comments[$key] );
}
}
return $comments;
}
add_filter( 'comments_array', 'wpturbo_filter_comments_by_author' );
This code snippet sets out to help users filter comments in WordPress by author, specifically to have comments only display for the author of a post in the WordPress admin panel.
The first part of the code, function wpturbo_filter_comments_by_author
, defines a new function that accepts a single parameter of $comments
passed by the comments_array
filter. This parameter holds an array of all the comments relating to a particular post.
The next line of code uses the get_current_user_id()
function to get the ID of the current user, i.e., the author of the post whose comments we want to display. This ID is saved in the $author_id
variable.
We then loop through the array of comments using a foreach
loop, checking each comment to see if its user ID matches the $author_id
. If the comment doesn’t belong to the current author, we remove it from the $comments
array using the unset()
function. We only keep comments that belong to the current author. The $key
variable in the foreach
loop represents the index of the current comment in the array.
Finally, we return the modified $comments
array to the comments_array
filter, and WordPress will display only the current author’s comments on their own posts in the WordPress admin panel. This code is especially useful when there are multiple users who edit posts, and each user wants to see only their comments on their posts.