How to move pagination links to the end of your content

Move pagination after content

If you’ve ever written a multi-page article before, you may have come across an annoyance where the links to the subsequent pages are not near the end of the content, but nestled well after related posts, sharing buttons and other miscellany that are tacked on to the end of the post. This is really bad UX because the user might not realise that there are more pages to the article, since they’re hidden away beneath items that usually signal that you’re at the end of an article. Here’s why this happens and how to resolve it.

Because there is no “after the content” hook in WordPress, plugins that want to display content after a post, like a mailing list sign-up, or social sharing icons are forced to add that content on to the end of the content itself, using the the_content filter.

On the other hand, the function that displays the pagination for a multi-page article, wp_link_pages(), is added to the loop in your theme files. So, a portion of your single.php or content-single.php file might look something like this:

In line 2, you see the function for displaying the post content. Remember that related post plugins and such modify this to put their additional content in this area, so this function will display the post content, swiftly followed by all these other “end-of-post” items. Then down on line 4, we have the wp_link_pages() function, which is why our pagination is showing up beneath the related posts and social sharing buttons.

To change this, we need to use the same trick that these other plugins use to tack the pagination on to the end of the content instead of calling it separately in the loop.

I wrote a new function for this purpose. This belongs in functions.php in your child theme, because it affects the layout of your site, and will not be required any more once you change themes.

In line 4, we declare a new variable, $pagination, which is equal to the wp_link_pages function from your single.php or content-single.php file. Bear in mind that you’ll need to remove this function from single.php or content-single.php, otherwise the pagination will be showing up in two places once we’ve added this function.

It is important to add the ‘echo’ => 0 parameter for this function to work correctly, which probably isn’t present in the function already in your theme.

In line 11, we’re adding the pagination to the end of the content, and perhaps the most important part is in line 16, where we apply the the_content filter at a priority of 1, so that we make sure it runs before all the other items trying to do the same thing, thus putting it immediately after the content.

When you refresh your site, you should now see your pagination directly after the content on each page, making it much easier to navigate through a multi-page article.

Leave a Reply