Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hawkidoki/c1caa4c4fdbe114d35168eb7291231f4 to your computer and use it in GitHub Desktop.
Save hawkidoki/c1caa4c4fdbe114d35168eb7291231f4 to your computer and use it in GitHub Desktop.
<?php
add_filter('posts_clauses', 'hwk_wp_query_order_by_taxonomy_terms', 10, 2);
function hwk_wp_query_order_by_taxonomy_terms($clauses, $wp_query){
global $wpdb;
if(!isset($wp_query->query['orderby']) || strpos($wp_query->query['orderby'], 'tax_') !== 0)
return $clauses;
$taxonomy = substr_replace($wp_query->query['orderby'], '', 0, strlen('tax_'));
$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 = '{$taxonomy}' OR taxonomy IS NULL)";
$clauses['groupby'] = "rel2.object_id";
$clauses['orderby'] = "GROUP_CONCAT({$wpdb->terms}.name ORDER BY name ASC) " . (strtoupper($wp_query->get('order')) == 'ASC') ? "ASC" : "DESC";
return $clauses;
}
// Usage:
//
// $query = new WP_Query(array(
// 'tax_query' => array(
// array(
// 'taxonomy' => 'category',
// 'field' => 'slug',
// 'terms' => 'my-category'
// )
// ),
// 'orderby' => 'tax_category' // Taxonomy: category
// 'order' => 'DESC'
// ));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment