WordPress includes a couple of handy functions for retrieving the links to “previous” and “next” posts. They are
get_next_post_link(). These functions, while useful for retrieving/outputting a simple link (HTML gets output), don’t allow for much customization to the actual output. In my opinion, they’re also strange functions to work with. There must be a better way, right? Of course!
Instead of calling these functions to get the entire link markup, we can use some of the functions’ source to retrieve only the permalink. This lets us create our own links that can be customized until our hearts are content. To do this, we retrieve the ID of the adjacent post object and pass it through
get_permalink(), like so:
get_adjacent_post() function is similar to
get_post() in that it retrieves the entire post object. The difference is that it retrieves no more than one post at a time and the post it gets is adjacent to the current post, meaning before or after in terms of date published. If the current post is the most recent,
get_adjacent_post() will return null (nothing) for the next post and, if the current post is the oldest, it will return null for the previous post. Therefore, it’s advisable to check if the ID exists.
Leave a Reply