Created
May 8, 2018 16:39
-
-
Save hwkdev/c1caa4c4fdbe114d35168eb7291231f4 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
<?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