Skip to content

Instantly share code, notes, and snippets.

@danlapteacru
Created September 1, 2021 14:31
Show Gist options
  • Save danlapteacru/5ba6c1cac1569cc07dc6cc52355ef6df to your computer and use it in GitHub Desktop.
Save danlapteacru/5ba6c1cac1569cc07dc6cc52355ef6df to your computer and use it in GitHub Desktop.
Order posts by taxonomy terms name
<?php
add_filter('posts_clauses', function (array $clauses, WP_Query $wp_query): array {
$wpdb = $GLOBALS['wpdb'];
$taxonomy = 'course_level';
if (! isset($wp_query->query['orderby']) || $taxonomy !== $wp_query->query['orderby']) {
return $clauses;
}
$clauses['join'] .= <<<SQL
LEFT OUTER JOIN {$wpdb->term_relationships} ON {$wpdb->posts}.ID={$wpdb->term_relationships}.object_id
LEFT OUTER JOIN {$wpdb->term_taxonomy} USING (term_taxonomy_id)
LEFT OUTER JOIN {$wpdb->terms} USING (term_id)
SQL;
$clauses['where'] .= " AND (taxonomy = '{$taxonomy}' OR taxonomy IS NULL)";
$clauses['groupby'] = 'object_id';
$clauses['orderby'] = "GROUP_CONCAT({$wpdb->terms}.name ORDER BY name ASC) ";
$clauses['orderby'] .= 'ASC';
return $clauses;
}, 10, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment