Recently I came across a requirement at work where I had to find out if a particular post had pagination (page-breaks) and if yes then whether the user is on the last of those pages.
Even though this sounded simple, I had to dig into WordPress core source code to find out a way to solve it since there were no helper functions and you have to use global variables to figure it out.
I thought of writing about my findings here so that it would be helpful to others and I would also know where to look up when I need to do it again 🙂
Pagination vs Page breaks
WordPress has two types of paginations.
- Pagination at list of post level
- Pagination at post level (Page breaks)
Pagination at list of post level
This is the most commonly used pagination, where you split a list of posts into different pages. Eg: In the blog homepage, the list of posts are ordered by post date and are split into different pages, so that each page displays about 10-15 posts. The same thing is also done in any archive pages where the posts are listed by category, tag, author etc.
WordPress has a set of helper functions for pagination that you can use in your theme to get this pagination to work.
Pagination at post leave (Page Breaks)
WordPress also allows you to split an individual post into multiple pages. This is used when you have a really long post and you want to split it up into multiple pages. This is done by inserting page breaks tag
<!--nextpage--> with in the content.
This is not very common. In your theme you can the
wp_link_pages to output the navigation, but you don’t have any helper functions to find out which page you are on.
Global variables to the rescue
Even though we don’t have helper functions to find out about pages based on page links, there are a couple of global variables that have this information.
$multipage(boolean) Flag to know if the current post has multiple pages or not. Returns true if the post has multiple pages.
$numpages(int) Total number of pages in the post.
$page(int) The current page number of the post being viewed.
Finding out if you are in the last page
Now, back to my requirement which made me to research this 🙂
My requirement was to find out if the user is currently viewing the last page of the post.
Using the above global variables I came up with the following little helper function.
Hope this saves time for someone else 🙂