Using WordPress ‘posts_orderby_request’ PHP filter

posts_orderby_request is a WordPress PHP filter that allows you to modify the ORDER BY clause of a query, primarily used by caching plugins.

Usage

add_filter('posts_orderby_request', 'my_custom_orderby', 10, 2);

function my_custom_orderby($orderby, $query) {
    // your custom code here
    return $orderby;
}

Parameters

  • $orderby (string) – The ORDER BY clause of the query.
  • $query (WP_Query) – The WP_Query instance (passed by reference).

More information

See WordPress Developer Resources: posts_orderby_request

Examples

Change Order by Post Title

Sorts the posts alphabetically by their title in ascending order.

add_filter('posts_orderby_request', 'orderby_post_title', 10, 2);

function orderby_post_title($orderby, $query) {
    global $wpdb;

    $orderby = "{$wpdb->prefix}posts.post_title ASC";
    return $orderby;
}

Order by Post Views

Sorts the posts by their view count in descending order.

add_filter('posts_orderby_request', 'orderby_post_views', 10, 2);

function orderby_post_views($orderby, $query) {
    global $wpdb;

    $orderby = "{$wpdb->prefix}postmeta.meta_value+0 DESC";
    return $orderby;
}

Order by Custom Field

Sorts the posts by a custom field in ascending order.

add_filter('posts_orderby_request', 'orderby_custom_field', 10, 2);

function orderby_custom_field($orderby, $query) {
    global $wpdb;

    $orderby = "{$wpdb->prefix}postmeta.meta_value ASC";
    return $orderby;
}

Order by Comment Count

Sorts the posts by the number of comments in descending order.

add_filter('posts_orderby_request', 'orderby_comment_count', 10, 2);

function orderby_comment_count($orderby, $query) {
    global $wpdb;

    $orderby = "{$wpdb->prefix}posts.comment_count DESC";
    return $orderby;
}

Random Post Order

Sorts the posts randomly.

add_filter('posts_orderby_request', 'orderby_random', 10, 2);
function orderby_random($orderby, $query) {
    $orderby = 'RAND()';
    return $orderby;
}