WordPress.org

Ready to get started?Download WordPress

Codex

Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Plugin API/Filter Reference/posts groupby

Description

The posts_groupby filters the GROUP BY clause of the SQL query for posts performed by the WP_Query() class.

Important

If you come with MySQL knowledge, the GROUP BY clause is pretty useless without the ability to modify the SELECT statement.

There is no SELECT filter since the query is supposed to return only the post data. The GROUP BY clause is set only when there are Custom Field Parameters for querying by post meta or Taxonomy Parameters for querying by taxonomy.

The default posts_groupby is set to {$wpdb->posts}.ID, which means that even if there are multiple results because of multiple meta and taxonomy, they are grouped together by the post id.

Usage

<?php add_filter( 'posts_groupby', 'my_posts_groupby' ); ?>

Example

add_filter( 'posts_groupby', 'my_posts_groupby' );
function my_posts_groupby($groupby) {
    global $wpdb;
    $groupby = "{$wpdb->posts}.ID";
    return $groupby;
}

The code above will just set the GROUP BY clause whether or not, a taxonomy query or a meta query is present.

For example, say we have a custom table (for ratings) and we wish to filter the posts using data from this table (only show posts that have a 5 star rating).

We can use the posts_join filter to join the tables. If there are multiple entries in the ratings table, the join can return multiple results for the same post.

We can make sure that we only have one row per post (that has all the entries for the ratings) by setting the GROUP BY clause. Remember that in the default query, GROUP BY clause is only set when there is a meta query or taxonomy query involved.

Return to Plugin API/Filter Reference