I'm using pre_get_posts to adjust the main query of the taxonomy term archive.

What I would like to accomplish is that the output is listed by post_type. I have a total of 4 post types and I want to order them as profile, page, post, letter.

I have tried already a few different order_by parameters, but no luck yet in getting it right.

I already have come a bit further by adding a posts_groupby filter (and removing it again after the query) and although the output is now indeed per post_type, it still is not in the desired order.

This is what I have come up with so far:

add_action('pre_get_posts', 'woo_taxonomy_posttype_filter' );
function so_groupby_cpt( $groupby ) {
    if ( preg_match( "/(|[ ,.])id(|[ ,])/i", $groupby ) )
        $groupby = 'post_type';
    return $groupby;

function woo_taxonomy_posttype_filter( $query ) {

global $wp_query;

if ( $query->is_tax && ! is_admin() ) {

add_filter( 'posts_groupby', 'so_groupby_cpt' );

$query->set('orderby','menu_order title');


remove_filter( 'posts_groupby', 'so_groupby_cpt' );

return $query;


Is this at all possible or am I asking for the impossible?


1 Answer 1


You should have a look at this answer.

Group by isn't what you want. WordPress, by default, groups by post ID to eliminate duplicate posts from the list. Since you'll need to group by ID and post_type, there will always be only a single combination of post_type and ID (your group by will do nothing, in other words).

Instead of hooking into post_groupby use posts_orderby. And you add an order by post type, even getting really granular with a SQL FIELD function:

add_filter('posts_orderby', 'wpse87578_posts_orderby', 10, 2);
function wpse87578_posts_orderby($orderby, $query)
    global $wpdb;

    if (is_admin() || !$query->is_main_query() || !is_tax()) {
        return $orderby;

    $new = "FIELD({$wpdb->posts}.post_type, 'profile', 'page', 'post', 'letter') ASC";

    if ($orderby) {
        $orderby = $new . ', ' . $orderby;
    } else {
        $orderby = $new;

    return $orderby;
  • thanks for your input @chrisguitarguy, but I am afraid that I don't entirely understand. If I replace my filter with yours, nothing changes, same output as I had already remains. What am I missing?
    – user2015
    Feb 20, 2013 at 6:19
  • btw checking the link you gave me now...
    – user2015
    Feb 20, 2013 at 6:25
  • nah, can't get it to work...
    – user2015
    Feb 20, 2013 at 6:49
  • have decided that I will stick with my original groupby filter, because at least then the posts are actually grouped by type. Not in the exact order I want them to be, but better than the alternative
    – user2015
    Feb 20, 2013 at 15:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.