Skip to content

Instantly share code, notes, and snippets.

@willybahuaud
Created November 14, 2019 15:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willybahuaud/0090584a0d1b6c875ceae9966bfe9ba8 to your computer and use it in GitHub Desktop.
Save willybahuaud/0090584a0d1b6c875ceae9966bfe9ba8 to your computer and use it in GitHub Desktop.
Order by taxonomy terms
<?php
add_action( 'pre_get_posts', 'w_filter_query' );
function w_filter_query( $q ) {
if ( ! is_admin() && $q->is_main_query() && is_post_type_archive( 'recipe' ) ) {
$q->set( 'posts_per_page', -1 );
$q->set( 'need_special_order', 'type-recette' );
}
}
add_filter('posts_clauses', 'w_orderby_tax_clauses', 10, 2 );
function w_orderby_tax_clauses( $clauses, $wp_query ) {
if ( $wp_query->get( 'need_special_order' ) && '' != $wp_query->get( 'need_special_order' ) ) {
$taxonomy = $wp_query->get( 'need_special_order' );
global $wpdb;
$clauses['join'] .="
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)
";
$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' == strtoupper( $wp_query->get('order') ) ) ? 'ASC' : 'DESC';
}
return $clauses;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment