When determining which post to use as next or previous post the call to next_post_link should order posts by title instead of default behaviour: by date of creation.
I found the answer to previous question, but now I am having problems implementing it. To change the ordering of posts in next_post_link I added a filter on ‘get_{$adjacent}_post_sort’ hook which is applied inside get_adjacent_post() when constructing the query.
relevant code from get_adjacent_post() in wp-includes/link-template.php
$adjacent = $previous ? 'previous' : 'next';
$op = $previous ? '<' : '>';
$order = $previous ? 'DESC' : 'ASC';
$join = apply_filters( "get_{$adjacent}_post_join", $join, $in_same_cat, $excluded_categories );
$where = apply_filters( "get_{$adjacent}_post_where", $wpdb->prepare("WHERE p.post_date $op %s AND p.post_type = 'post' AND p.post_status = 'publish' $posts_in_ex_cats_sql", $current_post_date), $in_same_cat, $excluded_categories );
$sort = apply_filters( "get_{$adjacent}_post_sort", "ORDER BY p.post_date $order LIMIT 1" );
return $wpdb->get_row("SELECT p.* FROM $wpdb->posts AS p $join $where $sort");
here is relevant plugin code: (WPD_print prints debuging messages to bottom of page. )
function filter_next_post_sort($sort) {
$sort = "ORDER BY p.post_title ASC LIMIT 1";
WPD_print('next sort: '.$sort);
return $sort;
}
function filter_previous_post_sort($sort) {
$sort = "ORDER BY p.post_title DESC LIMIT 1";
WPD_print('previous sort: '.$sort);
return $sort;
}
function filter_next_post_where($where) {
WPD_print('next where: '.$where);
return $where;
}
function filter_previous_post_where($where) {
WPD_print('previous where: '.$where);
return $where;
}
add_filter('get_next_post_sort', 'filter_next_post_sort');
add_filter('get_next_post_where', 'filter_next_post_where');
add_filter('get_previous_post_sort', 'filter_previous_post_sort');
add_filter('get_previous_post_where', 'filter_previous_post_where');
filter_next_post_sort and filter_previous_post_sort replace ordering to use post_title. filter_next_post_where and filter_previous_post_where need to modify the where clause to remove post_date restrictions. For some reason I can’t get wordpress to call get_next_post_where and get_previous_post_where..
get_next_post_sort and get_previous_post_sort get called with no problems and filter functions get called and print debugging message.