The posts_orderby filter allows you to modify the ORDER BY clause of a WordPress query, providing custom sorting options for your posts.
Usage
add_filter('posts_orderby', '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
Examples
Order posts by title in descending order
This code orders the posts by their title in a descending order (Z to A).
add_filter('posts_orderby', 'orderby_title_desc', 10, 2); function orderby_title_desc($orderby, $query) { global $wpdb; $orderby = "{$wpdb->prefix}posts.post_title DESC"; return $orderby; }
Random post order
This code shuffles the posts order randomly.
add_filter('posts_orderby', 'orderby_random', 10, 2); function orderby_random($orderby, $query) { global $wpdb; $orderby = "RAND()"; return $orderby; }
Order posts by comment count
This code orders the posts by the number of comments in descending order (most commented first).
add_filter('posts_orderby', 'orderby_comment_count', 10, 2); function orderby_comment_count($orderby, $query) { global $wpdb; $orderby = "{$wpdb->prefix}posts.comment_count DESC"; return $orderby; }
Order posts by custom field value
This code orders the posts by a custom field value, in this case, ‘my_custom_field’ in ascending order.
add_filter('posts_orderby', 'orderby_custom_field', 10, 2); function orderby_custom_field($orderby, $query) { global $wpdb; $orderby = "{$wpdb->prefix}postmeta.meta_value ASC"; $query->query_vars['meta_key'] = 'my_custom_field'; return $orderby; }
Order posts by multiple criteria
This code orders the posts by a custom field value ‘priority’ in descending order, and then by post date in ascending order.
add_filter('posts_orderby', 'orderby_priority_and_date', 10, 2); function orderby_priority_and_date($orderby, $query) { global $wpdb; $orderby = "{$wpdb->prefix}postmeta.meta_value DESC, {$wpdb->prefix}posts.post_date ASC"; $query->query_vars['meta_key'] = 'priority'; return $orderby; }