wp_query orderby title and meta key value (WP3.1)

You can filter the orderby part of the query to get what you want (trying to pass it via the orderby parameter will not work, it will be filtered out). This simple example adds the meta_value sort order before the standard title sort order.

add_filter( 'posts_orderby', 'wpse15168_posts_orderby' );
$query = new WP_Query( array(
    'meta_key' => 'interesting',
    'orderby' => 'title',
    'order' => 'ASC',
) );
remove_filter( 'posts_orderby', 'wpse15168_posts_orderby' );

function wpse15168_posts_orderby( $orderby )
{
    global $wpdb;
    $orderby = $wpdb->postmeta . '.meta_value DESC, ' . $orderby;
    return $orderby;
}

Leave a Comment

tech