Get the right prev/next post link when order posts by menu_order

There are 2 functions in WordPress to let you display previous and next post links: previous_post_link and next_post_link. In general, they work so well and really save a bunch time when coding a theme.

Recently in one of my projects, I created several custom post types, and made the posts ordered by menu_order. In such scenario, I found the previous and next post links didn’t behave as I expected, they still return the links based on the order of post ids.

Before I started to write my own version of previous_post_link, luckily I found the filters in get_adjacent_post could order the posts as I want. Here’s the snippet I use in my project:

At first I just added filters to change the sort, but it didn’t work. Then I realised the get_{$adjacent}_post_where should be filtered either, to help the SQL get the right posts for us to sort.

If you are interested in how to make the prev/next post links ordered by meta value, please read this thread on StackExchange for more information.