Custom query to order by multiple taxonomies

Well, in case anyone is searching and trying to find a way to do what I did here, I figured it out myself.

My task was: I have a custom post type called vehicle and there are two taxonomies, the vehicle maker and the vehicle model. I needed to show all the posts alphabetically ordered first by maker, then by model, so on the list it makes sense, exempla: Audi A1, Audi A4, BMW 120, etc.

It is easy to order by one taxonomy only, but if I just order by maker, my posts would show like Audi A4, Audi A1, Audi A3.

I solved this by doing this.

First, I’ll do a regular get_results so I can get an alphabetical order of all my makers:

 $makers_list = $wpdb->get_results("SELECT 
GROUP_CONCAT(pm.post_id ) as id_carro, tm.name as maker
    FROM wpav_postmeta pm
    INNER JOIN wpav_terms tm ON tm.term_id = pm.meta_value
    WHERE pm.meta_key='make'
    GROUP BY tm.name
    ORDER BY tm.name
    ");

The “GROUP_CONTACT” function of mysql will return me a list of post IDs, something like 19,49,59,83,58,395,394 etc

Then, I do a foreach on each maker and get an order list of vehicles for that particular maker, order by the model taxonomy.

foreach ( $makers_list as $maker ) {

$vehicle_list = $wpdb->get_results("SELECT tm.name as model , pm.post_id
FROM wpav_postmeta pm
INNER JOIN wpav_terms tm ON tm.term_id = pm.meta_value
WHERE pm.post_id IN (" . $fabr->vehicle_id . ") and pm.meta_key='model'
ORDER BY model
");

Then it is just a matter of doing another foreach for each of those cars

foreach ( $vehicle_list as $vehicle ) {

$status_post = get_post_status($vehicle->post_id);
$type_post = get_post_type($vehicle->post_id);

if ( $status_post == 'publish' && $type_post == 'vehicle') {
$post = get_post($vehicle->post_id);

As you can see I am checking if the post is published and it is the correct post type, then I set up the post variable and it’s done, normal wordpress loop after that.

Hope I could be of any help.