WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

On my search page I want to group the posts by post type. To do this I've got the following:

add_filter('posts_groupby', 'group_by_post_type' );
function group_by_post_type( $groupby ) {
  global $wpdb;
  if( is_search() ) {
     return $wpdb->posts.'.post_type';


Before adding the filter I had 9 results, however after adding the filter I only have 3 results, one of each post type.

What am I doing wrong?

share|improve this question

Your filter will result in SQL query with GROUP BY statement but without aggregate function. This will result in displaying only the first row that appear in the group that match your query and omitting the subsequent rows. Read this question for more details.

If you want to order your results by post_type, you can hook to posts_orderby filter instead:

add_filter('posts_orderby', 'group_by_post_type', 10, 2);
function group_by_post_type($orderby, $query) {
    global $wpdb;
    if ($query->is_search) {
        return $wpdb->posts . '.post_type DESC';
    // provide a default fallback return if the above condition is not true
    return $orderby;
share|improve this answer
Thanks - that worked great! – Steven Jones Dec 5 '12 at 12:24

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.