The get_pagenum_link() WordPress PHP function retrieves the link for a specified page number.
Usage
get_pagenum_link( $pagenum, $escape )
Example: get_pagenum_link( 3, true )
Parameters
$pagenum (int)
(Optional) – Page number. Default: 1$escape (bool)
(Optional) – Whether to escape the URL for display, withesc_url()
. If set to false, prepares the URL withsanitize_url()
. Default: true
More information
See WordPress Developer Resources: get_pagenum_link()
Examples
Basic Usage
Create a link to the third page of posts.
$page_number = 3; $page_link = get_pagenum_link( $page_number ); echo '<a href="' . $page_link . '">Page 3</a>';
Custom Pagination
Create custom pagination for a set of posts.
$total_pages = 5; for ( $i = 1; $i <= $total_pages; $i++ ) { $page_link = get_pagenum_link( $i ); echo '<a href="' . $page_link . '">Page ' . $i . '</a>'; }
Previous and Next Page Links
Create links to the previous and next pages.
$current_page = 2; $previous_page_link = get_pagenum_link( $current_page - 1 ); $next_page_link = get_pagenum_link( $current_page + 1 ); echo '<a href="' . $previous_page_link . '">Previous Page</a>'; echo '<a href="' . $next_page_link . '">Next Page</a>';
Displaying Links with Escaped URLs
Display links to the first five pages with escaped URLs.
for ( $i = 1; $i <= 5; $i++ ) { $page_link = get_pagenum_link( $i, true ); echo '<a href="' . $page_link . '">Page ' . $i . '</a>'; }
Displaying Links with Sanitized URLs
Display links to the first five pages with sanitized URLs.
for ( $i = 1; $i <= 5; $i++ ) { $page_link = get_pagenum_link( $i, false ); echo '<a href="' . $page_link . '">Page ' . $i . '</a>'; }