Skip to content

Instantly share code, notes, and snippets.

@stormwild
Forked from jnlsn/functions.php
Last active July 24, 2017 15:05
Show Gist options
  • Save stormwild/655ee8086e3c07905842 to your computer and use it in GitHub Desktop.
Save stormwild/655ee8086e3c07905842 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;
}
@smitralph
Copy link

Hi,

Exactly what I need, but I can't seem to get it to work. I realize this hasn't been active for a while, but maybe someone could help me... I added this script in my functions.php (after changing the > -signs back to code.. what is that?) but it won't work. The script gets executed, I tested that, but mainly the IF statement isn't met... If I simply change that to the simplest form (I used if (!is_admin() ), than the result is that I get only one post in stead of a sorted list...

Any ideas?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment