Last active
February 20, 2022 20:28
-
-
Save jnlsn/12f3a586900aa6759639 to your computer and use it in GitHub Desktop.
WP Query Orderby Taxonomy Term Name
This file contains 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
add_filter('posts_clauses', 'posts_clauses_with_tax', 10, 2); | |
function posts_clauses_with_tax( $clauses, $wp_query ) { | |
global $wpdb; | |
//array of sortable taxonomies | |
$taxonomies = array('example-taxonomy', 'other-taxonomy'); | |
if (isset($wp_query->query['orderby']) && in_array($wp_query->query['orderby'], $taxonomies)) { | |
$clauses['join'] .= " | |
LEFT OUTER JOIN {$wpdb->term_relationships} AS rel2 ON {$wpdb->posts}.ID = rel2.object_id | |
LEFT OUTER JOIN {$wpdb->term_taxonomy} AS tax2 ON rel2.term_taxonomy_id = tax2.term_taxonomy_id | |
LEFT OUTER JOIN {$wpdb->terms} USING (term_id) | |
"; | |
$clauses['where'] .= " AND (taxonomy = '{$wp_query->query['orderby']}' OR taxonomy IS NULL)"; | |
$clauses['groupby'] = "rel2.object_id"; | |
$clauses['orderby'] = "GROUP_CONCAT({$wpdb->terms}.name ORDER BY name ASC) "; | |
$clauses['orderby'] .= ( 'ASC' == strtoupper( $wp_query->get('order') ) ) ? 'ASC' : 'DESC'; | |
} | |
return $clauses; | |
} |
Thank you so much ! I spent hours searching for a solution, some of what I found on the net was really disgusting : aggregation of multiple query results (one by taxonomy term), retrieving all posts to sort them and then apply a pagination in PHP, etc...
This is by far the cleanest solution ! I had to twist it a bit of course, but you saved me a lot of time. Thanks again !
Great, thanks a lot.
In case anyone is trying to order by integer and you want 1,2,3,4 instead of 1,10,11,12 etc replace:
$clauses['orderby'] = "GROUP_CONCAT({$wpdb->;terms}.name ORDER BY name ASC) ";
with
$clauses['orderby'] = "CAST(GROUP_CONCAT({$wpdb->terms}.name ORDER BY name ASC) as DECIMAL) ";
+1 works great.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Kudos. Needed this badly and it works likes a charm.