Skip to content

Instantly share code, notes, and snippets.

@dhavalgshah
Forked from jnlsn/functions.php
Created May 9, 2018 06:09
Show Gist options
  • Save dhavalgshah/14cc5d36ca06fbe20dd774d79bbe97ca to your computer and use it in GitHub Desktop.
Save dhavalgshah/14cc5d36ca06fbe20dd774d79bbe97ca 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment