I want to output a list of guides, where each guide has votes and rating. So I want to sort the guide list by rating and votes.
Example:
Guide Name Rating Votes
Guide1 10 3
Guide2 10 2
Guide3 10 1
Guide4 9 6
Guide5 9 2
So I have to order the guides by 2 meta_key with are
omvp_vote_rating and omvp_total_vote
I have tried many many ways to get it work, but haven't got it yet. There is one way I almost have it working, but the problem is that I can't get it to order by meta_key, I can only order it by normal field like comment_count, modified, date, rand (random), title ...
So here is my code
$args = array(
'post_type' => 'guides',
'meta_key' => 'omvp_vote_rating',
'post_status' => 'publish',
'posts_per_page' => 20,
'meta_query' => array(
array(
'key' => 'omvp_vote_rating',
'compare' => '>=',
'value' => 0
),
array(
'key' => 'omvp_total_vote',
'compare' => '>=',
'value' => 0
),
),
'orderby' => array(
'title' => 'ASC', //<- This is working
'omvp_total_vote' => 'DESC' //<- This is not working
),
);
$wp_query = new WP_Query( $args );
You can do so by custom select query instead.
$query = "SELECT * FROM $wpdb->posts
LEFT JOIN $wpdb->postmeta AS rating ON(
$wpdb->posts.ID = rating.post_id
AND rating.meta_key = 'omvp_vote_rating'
)
LEFT JOIN $wpdb->postmeta AS vote ON(
$wpdb->posts.ID = vote.post_id
AND vote.meta_key = 'omvp_total_vote'
)
WHERE $wpdb->term_taxonomy.term_id = 3
AND $wpdb->posts.post_status = 'publish'
ORDER BY rating.meta_value, vote.meta_value ASC LIMIT 0,20"
$posts = $wpdb->get_results($query, object);