Skip to content

Instantly share code, notes, and snippets.

@jnlsn
Last active February 20, 2022 20:28
Show Gist options
  • Save jnlsn/12f3a586900aa6759639 to your computer and use it in GitHub Desktop.
Save jnlsn/12f3a586900aa6759639 to your computer and use it in GitHub Desktop.
WP Query Orderby Taxonomy Term Name
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;
}
@johngilesyoder
Copy link

Kudos. Needed this badly and it works likes a charm.

@jurv
Copy link

jurv commented May 3, 2018

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 !

Copy link

ghost commented May 4, 2018

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) ";

@ianhoyte
Copy link

ianhoyte commented Aug 8, 2019

+1 works great.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment