Skip to content

Instantly share code, notes, and snippets.

@ogorzalka
Created March 29, 2012 08:59
Show Gist options
  • Save ogorzalka/2235190 to your computer and use it in GitHub Desktop.
Save ogorzalka/2235190 to your computer and use it in GitHub Desktop.
Sorting by Taxonomy in WordPress
/*
Sorting by Taxonomy in WordPress
just add this file in your functions.php file
*/
function orderby_tax_clauses( $clauses, $wp_query ) {
global $wpdb;
$taxonomies = get_taxonomies();
foreach ($taxonomies as $taxonomy) {
if ( isset( $wp_query->query['orderby'] ) && $taxonomy == $wp_query->query['orderby'] ) {
var_dump($taxonomy);
$clauses['join'] .= " LEFT JOIN (
SELECT object_id, GROUP_CONCAT(name ORDER BY name ASC) AS $taxonomy
FROM $wpdb->term_relationships
INNER JOIN $wpdb->term_taxonomy USING (term_taxonomy_id)
INNER JOIN $wpdb->terms USING (term_id)
WHERE taxonomy = '$taxonomy'
GROUP BY object_id
) AS energy_terms ON ($wpdb->posts.ID = {$taxonomy}_terms.object_id)";
$clauses['orderby'] = "energy_terms.$taxonomy ";
$clauses['orderby'] .= ( 'ASC' == strtoupper( $wp_query->get('order') ) ) ? 'ASC' : 'DESC';
}
}
return $clauses;
}
add_filter( 'posts_clauses', 'orderby_tax_clauses', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment