WP-Query | Order a query two times by different custom field values

183 views Asked by At

I've been trying to pull the query off but I can't manage to do it. I want to query all the post in the category 'locales'. Then sort them by custom field value 'provincia', and then sort them by custom field value 'localidad'. I dont know if I'm being clear, I need to sort all 'locales' in for example, USA, and then sort those again by all the states. I've seen a lot of trick but no one worked.

I think the closer I got was this:

$entradas = new WP_Query( array (
    'post_type'      => 'post',
    'category_name'      => 'locales',
    'meta_query' => array(
             array(
                     'key' => 'provincia'
                     ),
             array(
                     'key' => 'localidad'
             )
         ),
    'orderby' => 'meta_value meta_value',
    'order' => 'ASC',
    'nopaging' => true,
    'posts_per_page' => -1
));

But of course it doesn't work. Do anyone know a solution? Help me!

Thank you!

1

There are 1 answers

0
Bhumi Shah On

For that you need to call custom query:

$querystr = "
    SELECT * FROM $wpdb->posts p
    LEFT JOIN $wpdb->postmeta pm1 ON p.ID = pm1.post_id
    LEFT JOIN $wpdb->postmeta pm2 ON p.ID = pm2.post_id
    LEFT JOIN $wpdb->term_relationships tr ON (p.ID = tr.object_id)
    LEFT JOIN $wpdb->term_taxonomy tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id)
    LEFT JOIN $wpdb->terms t ON (tt.term_id = t.term_id)
    WHERE t.name = 'locales'
    AND tt.taxonomy = 'category'
    AND p.post_status = 'publish'
    AND p.post_type = 'post'
    AND pm1.meta_key = 'provincia'
    AND pm2.meta_key = 'localidad'
    ORDER BY  pm1.meta_key,pm2.meta_key" ASC";