Using WordPress ‘comments_array’ PHP filter

The comments_array WordPress PHP filter allows you to modify the array of comments supplied to the comments template.

Usage

add_filter('comments_array', 'your_custom_function', 10, 2);

function your_custom_function($comments, $post_id) {
    // your custom code here
    return $comments;
}

Parameters

  • $comments (array): Array of comments supplied to the comments template.
  • $post_id (int): Post ID.

More information

See WordPress Developer Resources: comments_array

Examples

Reverse comment order

Reverse the order of the comments displayed.

add_filter('comments_array', 'reverse_comments_order', 10, 2);

function reverse_comments_order($comments, $post_id) {
    return array_reverse($comments);
}

Hide comments from specific user

Hide comments from a specific user by user ID.

add_filter('comments_array', 'hide_user_comments', 10, 2);

function hide_user_comments($comments, $post_id) {
    $hidden_user_id = 3; // Change to the user ID you want to hide comments from
    return array_filter($comments, function($comment) use ($hidden_user_id) {
        return $comment->user_id != $hidden_user_id;
    });
}