Using WordPress ‘posts_search_orderby’ PHP filter

The posts_search_orderby filter allows you to modify the ORDER BY clause used when ordering search results in WordPress.

Usage

add_filter('posts_search_orderby', 'my_custom_search_orderby', 10, 2);
function my_custom_search_orderby($search_orderby, $query) {
    // your custom code here
    return $search_orderby;
}

Parameters

  • $search_orderby (string): The ORDER BY clause.
  • $query (WP_Query): The current WP_Query instance.

More information

See WordPress Developer Resources: posts_search_orderby

Examples

Order search results by post date

To order search results by post date in descending order:

add_filter('posts_search_orderby', 'orderby_post_date', 10, 2);
function orderby_post_date($search_orderby, $query) {
    $search_orderby = 'post_date DESC';
    return $search_orderby;
}

Order search results by post title

To order search results alphabetically by post title:

add_filter('posts_search_orderby', 'orderby_post_title', 10, 2);
function orderby_post_title($search_orderby, $query) {
    $search_orderby = 'post_title ASC';
    return $search_orderby;
}

Order search results by comment count

To order search results by the number of comments in descending order:

add_filter('posts_search_orderby', 'orderby_comment_count', 10, 2);
function orderby_comment_count($search_orderby, $query) {
    $search_orderby = 'comment_count DESC';
    return $search_orderby;
}

Order search results by random order

To order search results randomly:

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

Order search results by custom field value

To order search results by a custom field value in ascending order:

add_filter('posts_search_orderby', 'orderby_custom_field', 10, 2);
function orderby_custom_field($search_orderby, $query) {
    global $wpdb;
    $search_orderby = "{$wpdb->prefix}postmeta.meta_value ASC";
    return $search_orderby;
}