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

The question:

I have a taxonomy wp_query and i would like to order the list by title and by meta value (numeric value)

  • Have a meta value Interesting = 1 or 0 in the posts
  • Not so interesting posts would be at the bottom of the query

GOAL – OUTPUT LIKE THIS: (is this possible with WP_QUERY and WP3.1)

A ( META KEY interesting = 1)

B ( META KEY interesting = 1)

C ( META KEY interesting = 1)

A ( META KEY interesting = 0)

B ( META KEY interesting = 0)

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 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;
}

Method 2

you can’t mix ascending and descending order, but if you switch the zeroes and ones then this might work:

$query = new WP_Query( array( 'meta_key => 'interesting',
                              'orderby' => 'meta_value_num title',
                              'order' => 'ASC' ) );


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment