posts_groupby_request is a WordPress PHP filter that allows you to modify the GROUP BY clause of a query. This filter is mainly used by caching plugins.
Usage
add_filter( 'posts_groupby_request', 'your_custom_function', 10, 2 );
function your_custom_function( $groupby, $query ) {
// your custom code here
return $groupby;
}
Parameters
- $groupby (string) – The GROUP BY clause of the query.
- $query (WP_Query) – The WP_Query instance (passed by reference).
More Information
See WordPress Developer Resources: posts_groupby_request
Examples
Group posts by year
Group posts by their published year.
add_filter( 'posts_groupby_request', 'group_posts_by_year', 10, 2 );
function group_posts_by_year( $groupby, $query ) {
global $wpdb;
$groupby = "{$wpdb->posts}.post_date";
return $groupby;
}
Group posts by author
Group posts by their author.
add_filter( 'posts_groupby_request', 'group_posts_by_author', 10, 2 );
function group_posts_by_author( $groupby, $query ) {
global $wpdb;
$groupby = "{$wpdb->posts}.post_author";
return $groupby;
}
Group posts by category
Group posts by their category.
add_filter( 'posts_groupby_request', 'group_posts_by_category', 10, 2 );
function group_posts_by_category( $groupby, $query ) {
global $wpdb;
$groupby = "{$wpdb->term_relationships}.term_taxonomy_id";
return $groupby;
}
Group posts by post type
Group posts by their post type.
add_filter( 'posts_groupby_request', 'group_posts_by_post_type', 10, 2 );
function group_posts_by_post_type( $groupby, $query ) {
global $wpdb;
$groupby = "{$wpdb->posts}.post_type";
return $groupby;
}
Group posts by month and year
Group posts by their published month and year.
add_filter( 'posts_groupby_request', 'group_posts_by_month_and_year', 10, 2 );
function group_posts_by_month_and_year( $groupby, $query ) {
global $wpdb;
$groupby = "MONTH({$wpdb->posts}.post_date), YEAR({$wpdb->posts}.post_date)";
return $groupby;
}