apply_filters_ref_array( ‘posts_groupby’, string $groupby, WP_Query $query )

Filters the GROUP BY clause of the query.

Parameters

$groupbystring
The GROUP BY clause of the query.
$queryWP_Query
The WP_Query instance (passed by reference).

More Information

  • 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.

Source

$groupby = apply_filters_ref_array( 'posts_groupby', array( $groupby, &$this ) );

Changelog

VersionDescription
2.0.0Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Example migrated from Codex:

    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.

You must log in before being able to contribute a note or feedback.