-
-
Save jnlsn/12f3a586900aa6759639 to your computer and use it in GitHub Desktop.
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; | |
} |
Thank you. It works perfectly and saved me hours of searching.
Hi,
Seems to be what I was looking for... but I'm new in php, and don't remember a lot my sql lessons...
What should I change to order posts by child term (hierarchical) instead of main tax ?
Would appreciate a lot your help... ! (please excuse my bad english, french guy here...)
Works like a champ, thanks!
Thank you
This saved my life! ;) Thank you!
Kudos. Needed this badly and it works likes a charm.
Thank you so much ! I spent hours searching for a solution, some of what I found on the net was really disgusting : aggregation of multiple query results (one by taxonomy term), retrieving all posts to sort them and then apply a pagination in PHP, etc...
This is by far the cleanest solution ! I had to twist it a bit of course, but you saved me a lot of time. Thanks again !
Great, thanks a lot.
In case anyone is trying to order by integer and you want 1,2,3,4 instead of 1,10,11,12 etc replace:
$clauses['orderby'] = "GROUP_CONCAT({$wpdb->;terms}.name ORDER BY name ASC) ";
with
$clauses['orderby'] = "CAST(GROUP_CONCAT({$wpdb->terms}.name ORDER BY name ASC) as DECIMAL) ";
+1 works great.
Found this by chance in a Google search, and it worked exactly as I needed. Thank you so much for sharing.