Last active
March 7, 2019 12:06
-
-
Save maxyudin/5026399c5d1b7f6561f67640a839bab7 to your computer and use it in GitHub Desktop.
[WordPress] Sort WP_Query results by multiple meta keeping Top Picks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* Source: https://www.billerickson.net/wp-query-sort-by-meta/ | |
*/ | |
// Query Arguments | |
$args = array( | |
'post_type' => 'review', | |
'posts_per_page' => 10, | |
'paged' => get_query_var( 'paged', false ), | |
'meta_query' => array( | |
'relation' => 'AND', | |
'be_top_pick' => array( | |
'key' => 'be_top_pick', | |
'compare' => 'EXISTS', | |
), | |
'be_price' => array( | |
'key' => 'be_price', | |
'type' => 'NUMERIC', | |
'compare' => 'EXISTS', | |
), | |
'be_rating' => array( | |
'key' => 'be_rating', | |
'type' => 'NUMERIC', | |
'compare' => 'EXISTS', | |
), | |
) | |
); | |
// Sort Results | |
$current_sort = isset( $_GET['hosting-sort'] ) ? esc_attr( $_GET['hosting-sort'] ) : 'most-recent'; | |
switch( $current_sort ) { | |
case 'most-recent': | |
$args['orderby'] = array( | |
'be_top_pick' => 'DESC', | |
'post_date' => 'DESC', | |
); | |
break; | |
case 'price-high': | |
$args['orderby'] = array( | |
'be_top_pick' => 'DESC', | |
'be_price' => 'DESC', | |
); | |
break; | |
case 'price-low': | |
$args['orderby'] = array( | |
'be_top_pick' => 'DESC', | |
'be_price' => 'ASC', | |
); | |
break; | |
case 'rating-high': | |
$args['orderby'] = array( | |
'be_top_pick' => 'DESC', | |
'be_rating' => 'DESC', | |
); | |
break; | |
case 'rating-low': | |
$args['orderby'] = array( | |
'be_top_pick' => 'DESC', | |
'be_rating' => 'ASC', | |
); | |
break; | |
} | |
$loop = new WP_Query( $args ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment