Using WordPress ‘get_page_of_comment’ PHP filter

The get_page_of_comment WordPress PHP filter calculates the page on which a specific comment appears.

Usage

add_filter('get_page_of_comment', 'your_custom_function', 10, 6);
function your_custom_function($page, $args, $original_args, $comment_id) {
    // your custom code here
    return $page;
}

Parameters

  • $page (int) – The calculated comment page.
  • $args (array) – Arguments used to calculate pagination.
  • $original_args (array) – Array of arguments passed to the function.
  • $comment_id (int) – ID of the comment.

More information

See WordPress Developer Resources: get_page_of_comment

Examples

Change the number of comments per page

This example changes the number of comments displayed per page to 10.

add_filter('get_page_of_comment', 'change_comments_per_page', 10, 6);
function change_comments_per_page($page, $args, $original_args, $comment_id) {
    $args['per_page'] = 10;
    // Recalculate comment page
    $page = ceil(($args['per_page'] - $comment_id) / $args['per_page']);
    return $page;
}

Display comments in reverse order

This example displays comments in reverse order, so the newest comments appear on the first page.

add_filter('get_page_of_comment', 'reverse_comment_order', 10, 6);
function reverse_comment_order($page, $args, $original_args, $comment_id) {
    $total_comments = get_comments_number();
    $reversed_page = ceil(($total_comments - $comment_id) / $args['per_page']);
    return $reversed_page;
}

Offset comment page numbering

This example offsets the comment page numbering by 1.

add_filter('get_page_of_comment', 'offset_comment_page_number', 10, 6);
function offset_comment_page_number($page, $args, $original_args, $comment_id) {
    return $page + 1;
}

Exclude comments from specific users

This example excludes comments from specific user IDs (1 and 2 in this case) when calculating comment pages.

add_filter('get_page_of_comment', 'exclude_comments_from_users', 10, 6);
function exclude_comments_from_users($page, $args, $original_args, $comment_id) {
    $comment = get_comment($comment_id);
    $excluded_users = array(1, 2);
    if (in_array($comment->user_id, $excluded_users)) {
        return false;
    }
    return $page;
}

Customize comment page calculation based on comment type

This example customizes the comment page calculation based on the comment type.

add_filter('get_page_of_comment', 'customize_comment_page_by_type', 10, 6);
function customize_comment_page_by_type($page, $args, $original_args, $comment_id) {
    $comment = get_comment($comment_id);
    if ($comment->comment_type == 'trackback') {
        $page = ceil(($args['per_page'] - $comment_id) / 5);
    }
    return $page;
}