Using WordPress ‘comments_clauses’ PHP filter

The comments_clauses WordPress PHP filter allows you to modify the SQL clauses used in comment queries.

Usage

add_filter('comments_clauses', 'my_custom_comments_clauses', 10, 2);

function my_custom_comments_clauses($clauses, $query) {
  // Your custom code here

  return $clauses;
}

Parameters

  • $clauses (string[]): An associative array of comment query clauses.
  • $query (WP_Comment_Query): Current instance of WP_Comment_Query (passed by reference).

More information

See WordPress Developer Resources: comments_clauses

Examples

Exclude comments by a specific user

Exclude comments made by a user with the user ID of 5.

add_filter('comments_clauses', 'exclude_user_comments', 10, 2);

function exclude_user_comments($clauses, $query) {
  global $wpdb;
  $clauses['where'] .= " AND {$wpdb->comments}.user_id != 5";
  return $clauses;
}

Order comments by title

Order comments by the title of the post they belong to.

add_filter('comments_clauses', 'order_comments_by_title', 10, 2);

function order_comments_by_title($clauses, $query) {
  global $wpdb;
  $clauses['orderby'] = "{$wpdb->posts}.post_title";
  return $clauses;
}

Filter comments by a custom field

Only show comments on posts with a specific custom field value.

add_filter('comments_clauses', 'filter_comments_by_custom_field', 10, 2);

function filter_comments_by_custom_field($clauses, $query) {
  global $wpdb;
  $clauses['join'] .= " INNER JOIN {$wpdb->postmeta} ON ({$wpdb->posts}.ID = {$wpdb->postmeta}.post_id)";
  $clauses['where'] .= " AND {$wpdb->postmeta}.meta_key = 'custom_field_name' AND {$wpdb->postmeta}.meta_value = 'custom_value'";
  return $clauses;
}

Limit comments per page

Limit the number of comments displayed per page to 5.

add_filter('comments_clauses', 'limit_comments_per_page', 10, 2);

function limit_comments_per_page($clauses, $query) {
  $clauses['limit'] = '5';
  return $clauses;
}

Exclude pingbacks and trackbacks

Exclude pingbacks and trackbacks from the comment query.

add_filter('comments_clauses', 'exclude_pingbacks_trackbacks', 10, 2);

function exclude_pingbacks_trackbacks($clauses, $query) {
  global $wpdb;
  $clauses['where'] .= " AND {$wpdb->comments}.comment_type NOT IN ('pingback', 'trackback')";
  return $clauses;
}