Usage of the new “posts_clauses” filter in WordPress 3.1?

Below is the query I found somewhere and was going through it. The purpose of query is to sort the posts based on taxonomy. So, I am sharing the code so it might help you understand the use of posts_clauses.

function color_clauses_mike( $clauses, $query ) {
global $wpdb;

if ( isset( $query->query['orderby'] ) && 'color' == $query->query['orderby'] ) {

    $clauses['join'] .= <<<SQL
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)
SQL;

    $clauses['where'] .= " AND (taxonomy = 'color' OR taxonomy IS NULL)";
    $clauses['groupby'] = "object_id";
    $clauses['orderby']  = "GROUP_CONCAT({$wpdb->terms}.name ORDER BY name ASC) ";
    $clauses['orderby'] .= ( 'ASC' == strtoupper( $query->get('order') ) ) ? 'ASC' : 'DESC';
}

return $clauses;
}
add_filter( 'posts_clauses', 'color_clauses_mike', 10, 2 );

here is the source where I found the above query: http://scribu.net/wordpress/sortable-taxonomy-columns.html

Leave a Comment