How to get post pagination like this

It’s not possible with wp_link_pages(), but you can use paginate_links(). You just need to configure the arguments so that the links are based on the pagination of your post/page. To do this you just need to know:

  • The base URL. This is the permalink of the page/post.
  • The format of the pagination portion of the URL. This is just the page number, like /6, and not /page/6 or /?page=5 or anything like that.
  • The total number of pages. This is the global $numpages variable.
  • The current page. This is the global $page variable.

Which you can use like this:

echo paginate_links(
    [
        'base'    => user_trailingslashit( trailingslashit( get_the_permalink() ) . '%_%' ),
        'format'  => '%#%',
        'total'   => $numpages,
        'current' => $page,
    ]
);

Note that we want base to be something like this, where %_% is where our page number will go:

http://website.test/2021/03/25/my-post/%_%/

To do this properly we use trailingslashit() on get_the_permalink() to guarantee that there is a slash between the URL and the placeholder. Then we use user_trailingslashit() to add a trailing slash to the very end in case the site is configured that way.

Leave a Comment