I'm looking for a method to order posts by a custom field so that the navigational links on a single post template would point to the next or previous post in the sequence defined by a number in a custom field. Note: The posts are all in the same category. I can define the list of posts in the category in the order defined by the custom field value but when I view the single post, with a template modified to show only the selected category, the nav links at the bottom of the page are based on chronological sequence. What I need is a way to link to the next/previous post in the same category, where the order is defined by the custom field value.

Is there anyway to override the chronological ordering of the posts?


1 Answer 1


Check out get_next_post_sort and get_previous_post_sort filters. You can modify the ORDER BY clause to whatever you want (including ). For example, if you want to sort the 'next post' to be the post with the smallest adjacent post ID:

function wp28041_get_next_post_sort($where){
    return 'ORDER BY ID ASC LIMIT 1';
add_filter('get_next_post_sort', 'wp28041_get_next_post_sort');

You don't have to replace the entire thing, you can also add to it. For example if you'd like to add a second ordering parameter, you can:

function wp28042_get_next_post_sort($where){
    return str_replace('LIMIT 1',  ', ID ASC LIMIT 1', $where);
add_filter('get_next_post_sort', 'wp28042_get_next_post_sort');
  • Thanks for your response - appreciated. I get the concept but I'm having difficulties implementing this with a custom field. If I replace the ID with the custom field do I use the wordpress terms so that I end up with something like "ORDER BY meta_key=sort-order ASC LIMIT 1"? I tried various forms of this approach unsuccessfully.In addition I notice you inserted a variable as input to the function, is this something required because its used in the WP Core or is it there because you used it in the second case?
    – dorich
    Apr 29, 2013 at 19:00
  • The whole point of filters is to modify something that is going through at a point in time. In this case this 'something' is the ORDER BY clause. I'm completely replacing it in the first case, and merely modifying it in the second. Apr 29, 2013 at 19:12
  • As for custom fields, they are stored in wp_postmeta table, so I imagine you will need to join that table in during your query. Hm, my suggestion may not work after all, since you don't have access to the entire query inside those hooks. Apr 29, 2013 at 19:13
  • Check this answer, apparently you can do sorting by a sub-query. Apr 29, 2013 at 19:15
  • Thanks for your suggestions, after spending more time on this I resorted to a plugin. I appreciate your help.
    – dorich
    Apr 30, 2013 at 1:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.