Scenario: I have a bunch of resellers loaded under a "reseller" post type. Each of these resellers have a "rating" which is a string value like Gold, Bronze, Silver - this indicates their status as a reseller. Each reseller is also categorised into a country.
What I have: I have made use of the pre_get_posts action to sort by meta_value, asc or desc. This is working fine.
function my_pre_get_posts( $query ) {
// do not modify queries in the admin
if( is_admin() ) {
return $query;
}
if( isset($query->query_vars['country']) ) {
$query->set('orderby', 'meta_value');
$query->set('meta_key', 'partner_status');
$query->set('order', 'ASC');
}
return $query;
}
add_action('pre_get_posts', 'my_pre_get_posts');
I want to instead be able to specify the sort order so that the Gold resellers are first, then the Silver resellers, then the Bronze ones, etc. So, pseudo code:
function my_pre_get_posts( $query ) {
// do not modify queries in the admin
if( is_admin() ) {
return $query;
}
if( isset($query->query_vars['country']) ) {
$query->set('orderby', ['Gold','Bronze','Silver']); // pseudo here
$query->set('meta_key', 'partner_status');
$query->set('order', 'ASC');
}
return $query;
}
add_action('pre_get_posts', 'my_pre_get_posts');
Hope this makes sense to someone! :)
the_posts
), with php.net/usort e.g.pre_get_posts
. This type of complex sorting is doable by default since v4.2. You can use this to get you startedusort()
to sort the posts viathe_posts
filter would be faster. To be honest, I haven't looked into performance testing this scenario. I know pre 4.2, I made use ofusort()
andthe_posts
alot to do custom sorting ;-)