Publish: 2015-08-14 | Modify: 2017-06-21
The recent comments widget provided by WordPress can display the latest comments on the blog and allows for customization of the number of comments to display. However, a drawback is that when the administrator replies to blog commenters, those replies are also displayed. This can lead to the recent comments widget being filled with the administrator's own comments, which is not ideal for user experience.
To solve this problem, you can simply add the following code to the functions.php file in your theme directory:
// Exclude admin comments from recent comments widget
// Check WP_Comment_Query::query in wp-includes/comment.php
// Improve the query conditions based on the passed parameters
add_filter( 'comments_clauses', 'wpdit_comments_clauses', 2, 10);
function wpdit_comments_clauses( $clauses, $comments ) {
global $wpdb;
if ( isset( $comments->query_vars['not_in__user'] ) && ( $user_id = $comments->query_vars['not_in__user'] ) ) {
if ( is_array( $user_id ) ) {
$clauses['where'] .= ' AND user_id NOT IN (' . implode( ',', array_map( 'absint', $user_id ) ) . ')';
} elseif ( '' !== $user_id ) {
$clauses['where'] .= $wpdb->prepare( ' AND user_id <> %d', $user_id );
}
}
//var_dump($clauses);
return $clauses;
}
// Check WP_Widget_Recent_Comments in wp-includes/default-widgets.php
// Add parameter not_in__user
add_filter( 'widget_comments_args', 'wpdit_widget_comments_args' );
function wpdit_widget_comments_args( $args ){
$args['not_in__user'] = array(1); // Replace with your own ID;
return $args;
}
//END
After adding this code, the recent comments widget on the right side of your website will no longer display comments from the administrator "小z", only user comments will be shown.
I come from China and I am a freelancer. I specialize in Linux operations, PHP, Golang, and front-end development. I have developed open-source projects such as Zdir, ImgURL, CCAA, and OneNav.