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

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)

Read More

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)

Related posts

Leave a Reply

2 comments

  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;
    }
    
  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' ) );