Query multiple post types – Order by type and post title title

Yes it is, and to also sort by the post title, you would just need to add , {$wpdb->posts}.post_title <ASC or DESC> after the FIELD(), like so which results in a clause that looks like ORDER BY FIELD(wp_posts.post_type, <types>), wp_posts.post_title ASC:

// Replace this:
return $orderby       = "FIELD( {$wpdb->posts}.post_type," . $post_type__in_string . ' )';

// with this:
return $orderby       = "FIELD( {$wpdb->posts}.post_type," . $post_type__in_string . ' )' . // wrapped
    ", {$wpdb->posts}.post_title ASC";

But as for sorting the posts by the post type, if you do not actually need to sort the posts in the same order you have them in the post_type array, then you could simply use an orderby array like so:

$args = array(
    'post_type' => array( 'post', 'cats', 'dogs', 'rabbits' ),
    'orderby'   => array(
        'post_type'  => 'ASC', // Sort by the post type.
        'post_title' => 'ASC', // Then, by the post title.
    ),
);

$query = new WP_Query( $args );
  • With the above example, the posts would be sorted like so:

    • Cats A
    • Cats B
    • Dogs A
    • Dogs B
    • Post A
    • Post B
    • Rabbits A
    • Rabbits B

    I.e. You would get cats, dogs, post, rabbits instead of post, cats, dogs, rabbits (note the post which is the first item in the post_type array).

tech