How to order posts by two meta values

October 15, 2013 at 4:20 pm

By default, WordPress allows you to sort results of a query by one meta value, but what if you need to sort results by two meta values (For example date and time)? Here ‘s a working example.

Paste the code below in your template file where you need to sort the results of the query.

<?php 

$query = "SELECT wposts.*, wpostmeta1.*, wpostmeta2.* 
FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta1, $wpdb->postmeta wpostmeta2
WHERE wposts.ID = wpostmeta1.post_id
AND wposts.ID = wpostmeta2.post_id
AND wpostmeta1.meta_key = 'date'
AND wpostmeta2.meta_key = 'time'
ORDER BY wpostmeta1.meta_value ASC,
         wpostmeta2.meta_value ASC";

$results = $wpdb->get_results($query);

foreach ( $results as $result ) {
         //output results as desired
} ?>

Please note that this query is given as an example and might need to be adapted to fit your specific needs. If you need help at a cheap rate, contact WPCAT.

Tags: