Using WordPress ‘posts_groupby’ PHP filter

The posts_groupby filter allows you to modify the GROUP BY clause of the WordPress query, which is used to group rows that have the same values in specified columns.

Usage

add_filter('posts_groupby', '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

Examples

Group Posts by Year

This example groups posts by the year they were published:

add_filter('posts_groupby', 'group_posts_by_year', 10, 2);

function group_posts_by_year($groupby, $query) {
  global $wpdb;
  $groupby = "{$wpdb->prefix}posts.post_date YEAR";
  return $groupby;
}

Group Posts by Author

Group posts by the author:

add_filter('posts_groupby', 'group_posts_by_author', 10, 2);

function group_posts_by_author($groupby, $query) {
  global $wpdb;
  $groupby = "{$wpdb->prefix}posts.post_author";
  return $groupby;
}

Group Posts by Category

Group posts by the category:

add_filter('posts_groupby', 'group_posts_by_category', 10, 2);

function group_posts_by_category($groupby, $query) {
  global $wpdb;
  $groupby = "{$wpdb->prefix}terms.term_id";
  return $groupby;
}

Group Posts by Month and Year

Group posts by the month and year they were published:

add_filter('posts_groupby', 'group_posts_by_month_and_year', 10, 2);

function group_posts_by_month_and_year($groupby, $query) {
  global $wpdb;
  $groupby = "MONTH({$wpdb->prefix}posts.post_date), YEAR({$wpdb->prefix}posts.post_date)";
  return $groupby;
}

Group Posts by Custom Field Value

Group posts by the value of a custom field:

add_filter('posts_groupby', 'group_posts_by_custom_field_value', 10, 2);
function group_posts_by_custom_field_value($groupby, $query) {
    global $wpdb;
    $groupby = "{$wpdb->prefix}postmeta.meta_value";
    return $groupby;
}