Using WordPress ‘get_{$adjacent}_post_sort’ PHP filter

The get_{$adjacent}_post_sort WordPress PHP filter allows you to modify the ORDER BY clause in the SQL for an adjacent post query. The dynamic part of the hook name, $adjacent, can be either ‘next’ or ‘previous’.

Usage

add_filter('get_next_post_sort', 'my_custom_next_post_sort', 10, 3);
function my_custom_next_post_sort($order_by, $post, $order) {
    // your custom code here
    return $order_by;
}

Parameters

  • $order_by (string): The ORDER BY clause in the SQL.
  • $post (WP_Post): WP_Post object.
  • $order (string): Sort order. ‘DESC’ for previous post, ‘ASC’ for next.

More information

See WordPress Developer Resources: get_{$adjacent}_post_sort

Examples

Sort posts by title

This example modifies the adjacent post query to order posts by their title.

add_filter('get_next_post_sort', 'sort_adjacent_posts_by_title', 10, 3);
function sort_adjacent_posts_by_title($order_by, $post, $order) {
    $order_by = "p.post_title {$order}";
    return $order_by;
}

Sort posts by publication date

This example sorts the adjacent posts by their publication date.

add_filter('get_next_post_sort', 'sort_adjacent_posts_by_date', 10, 3);
function sort_adjacent_posts_by_date($order_by, $post, $order) {
    $order_by = "p.post_date {$order}";
    return $order_by;
}

Sort posts by comment count

This example sorts the adjacent posts by their comment count.

add_filter('get_next_post_sort', 'sort_adjacent_posts_by_comment_count', 10, 3);
function sort_adjacent_posts_by_comment_count($order_by, $post, $order) {
    $order_by = "p.comment_count {$order}";
    return $order_by;
}

Sort posts by a custom field

This example sorts the adjacent posts by a custom field ‘my_custom_field’.

add_filter('get_next_post_sort', 'sort_adjacent_posts_by_custom_field', 10, 3);
function sort_adjacent_posts_by_custom_field($order_by, $post, $order) {
    global $wpdb;
    $order_by = "{$wpdb->postmeta}.meta_value {$order}";
    return $order_by;
}

Sort posts randomly

This example sorts the adjacent posts randomly.

add_filter('get_next_post_sort', 'sort_adjacent_posts_randomly', 10, 3);
function sort_adjacent_posts_randomly($order_by, $post, $order) {
    $order_by = "RAND()";
    return $order_by;
}