Using WordPress ‘pre_get_comments’ PHP action

The pre_get_comments WordPress PHP action fires before comments are retrieved, allowing you to modify the WP_Comment_Query instance.

Usage

add_action('pre_get_comments', 'your_custom_function');
function your_custom_function($query) {
  // your custom code here
}

Parameters

  • $query (WP_Comment_Query): Current instance of WP_Comment_Query (passed by reference).

More information

See WordPress Developer Resources: pre_get_comments

Examples

Exclude comments from a specific user

This code snippet will exclude comments from a specific user by setting the user ID in the query.

add_action('pre_get_comments', 'exclude_user_comments');
function exclude_user_comments($query) {
  $user_id = 5; // User ID to exclude
  $query->set('user_id', -$user_id);
}

Display only approved comments

This code snippet will display only approved comments by modifying the comment status.

add_action('pre_get_comments', 'show_only_approved_comments');
function show_only_approved_comments($query) {
  $query->set('status', 'approve');
}

Order comments by date

This code snippet will order comments by date in descending order.

add_action('pre_get_comments', 'order_comments_by_date_desc');
function order_comments_by_date_desc($query) {
  $query->set('orderby', 'comment_date');
  $query->set('order', 'DESC');
}

Limit comments per page

This code snippet will limit the number of comments displayed per page.

add_action('pre_get_comments', 'limit_comments_per_page');
function limit_comments_per_page($query) {
  $query->set('number', 10); // Limit to 10 comments per page
}

Exclude comments with specific words

This code snippet will exclude comments containing specific words by modifying the search parameter.

add_action('pre_get_comments', 'exclude_comments_with_specific_words');
function exclude_comments_with_specific_words($query) {
  $words_to_exclude = array('spam', 'troll');
  $search = '';
  foreach ($words_to_exclude as $word) {
    $search .= "comment_content NOT LIKE '%$word%' AND ";
  }
  $search = rtrim($search, " AND ");
  $query->set('search', $search);
}