How to order posts by two meta values

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.

Leave a Reply

Your email address will not be published. Required fields are marked *