Using WordPress ‘get_comments_pagenum_link()’ PHP function

The get_comments_pagenum_link() WordPress PHP function retrieves the comments page number link.

Usage

get_comments_pagenum_link( $pagenum, $max_page );

Example

// Retrieve the link for comments page number 2
$link = get_comments_pagenum_link( 2 );
echo $link;

Parameters

  • $pagenum (int) – Optional. Page number. Default: 1
  • $max_page (int) – Optional. The maximum number of comment pages. Default: 0

More information

See WordPress Developer Resources: get_comments_pagenum_link()

Examples

This example displays the link for comments page number 3.

$link = get_comments_pagenum_link( 3 );
echo 'Visit comments page 3: ' . $link;

This example displays links for all available comments pages.

// Get the total number of comments pages
$max_pages = get_comment_pages_count();

// Display links for each page
for ( $i = 1; $i <= $max_pages; $i++ ) {
    $link = get_comments_pagenum_link( $i );
    echo 'Page ' . $i . ': ' . $link . '<br />';
}

Display pagination for comments

This example displays pagination links for comments pages.

// Get the current comments page
$current_page = get_query_var( 'cpage' );

// Get the total number of comments pages
$max_pages = get_comment_pages_count();

// Display previous and next links
if ( $current_page > 1 ) {
    $prev_link = get_comments_pagenum_link( $current_page - 1 );
    echo '<a href="' . $prev_link . '">Previous</a>';
}
if ( $current_page < $max_pages ) {
    $next_link = get_comments_pagenum_link( $current_page + 1 );
    echo '<a href="' . $next_link . '">Next</a>';
}

Display a specific range of comments pages

This example displays links for comments pages 2 to 5.

// Display links for pages 2 to 5
for ( $i = 2; $i <= 5; $i++ ) {
    $link = get_comments_pagenum_link( $i );
    echo 'Page ' . $i . ': ' . $link . '<br />';
}

Display comments pages with custom range

This example displays links for comments pages with a custom range of 3 pages before and after the current page.

// Get the current comments page
$current_page = get_query_var( 'cpage' );

// Get the total number of comments pages
$max_pages = get_comment_pages_count();

// Set the range
$range = 3;

// Calculate the start and end pages
$start_page = max( 1, $current_page - $range );
$end_page = min( $max_pages, $current_page + $range );

// Display links for the custom range
for ( $i = $start_page; $i <= $end_page; $i++ ) {
    $link = get_comments_pagenum_link( $i );
    echo 'Page ' . $i . ': ' . $link . '<br />';
}