WordPress hwk Codes Trier une WP Query par les Noms des Termes d’une Taxonomie

Trier une WP Query par les Noms des Termes d’une Taxonomie

8 May 2018
<?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'
// ));


Konrad Chmielewski

Evangeliste WordPress & Full Stack Developer depuis 10 années.