Retrieving and displaying Comments with pagination

The code below shows how to display user comments with pagination links in WordPress. To do this, we need to use the WP_Comment_Query class.

Suppose we display comments on page /user-comments and we will use GET parameter ?pagenum=10 to add pagination page number. We are going to output 50 comments per page. We are going to use function paginate_links() to create HTML code for pagination links.

$per_page = 50;
$pagenum = $_GET['pagenum'] ?? 1;
$offset = ($pagenum - 1) * $per_page;
$paged_url_patt = home_url( preg_replace( '/[?&].*/', '', $_SERVER['REQUEST_URI'] ) ) .'?pagenum=%#%';

$query    = new WP_Comment_Query;
$comments = $query->query( [
	'order'   => 'DESC',
	'user_id' => $user_id,
	'offset'  => $offset,
	'number'  => $per_page,
	'no_found_rows'  => false,
] );

//$total_comments = (int) $query->found_comments;
$max_pages      = (int) $query->max_num_pages;

$paginate_links = paginate_links( [
	'base'    => $paged_url_patt,
	'current' => $pagenum,
	'total'   => $max_pages
] );

echo $paginate_links;

The result will be the following HTML code:

<a class="prev page-numbers" href="https://example.com/profile/comments?pagenum=2">← Prev</a>
<a class="page-numbers" href="https://example.com/profile/comments?pagenum=1">1</a>
<a class="page-numbers" href="https://example.com/profile/comments?pagenum=2">2</a>
<span aria-current="page" class="page-numbers current">3</span>
<a class="page-numbers" href="https://example.com/profile/comments?pagenum=4">4</a>
<a class="page-numbers" href="https://example.com/profile/comments?pagenum=5">5</a>
<span class="page-numbers dots">…</span>
<a class="page-numbers" href="https://example.com/profile/comments?pagenum=75">75</a>
<a class="next page-numbers" href="https://example.com/profile/comments?pagenum=4">Next →</a>

This Note embeded into: get_comments()