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)

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)

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x