Using WordPress ‘parse_comment_query’ PHP action

The parse_comment_query WordPress PHP action fires after the comment query variables have been parsed.

Usage

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

Parameters

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

More information

See WordPress Developer Resources: parse_comment_query

Examples

Modify the comment order

Change the comment order to display the newest comments first.

add_action('parse_comment_query', 'newest_comments_first');
function newest_comments_first($query) {
    $query->query_vars['order'] = 'DESC';
}

Exclude comments with a specific word

Exclude comments containing the word “spam” from the comment query.

add_action('parse_comment_query', 'exclude_spam_comments');
function exclude_spam_comments($query) {
    $query->query_vars['search'] = '-spam';
}

Show only approved comments

Modify the comment query to display only approved comments.

add_action('parse_comment_query', 'show_only_approved_comments');
function show_only_approved_comments($query) {
    $query->query_vars['status'] = 'approve';
}

Limit comments per page

Limit the number of comments displayed per page to 5.

add_action('parse_comment_query', 'limit_comments_per_page');
function limit_comments_per_page($query) {
    $query->query_vars['number'] = 5;
}

Exclude comments from a specific user

Exclude comments made by a user with a specific ID.

add_action('parse_comment_query', 'exclude_comments_from_user');
function exclude_comments_from_user($query) {
    $query->query_vars['user_id'] = -1; // Replace -1 with the user ID to exclude.
}