Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort multiple wordpress custom field values?

Display posts with 'Product' type ordered by 'Price' custom field:

$query = new WP_Query( 
                      array ( 'post_type' => 'product', 
                              'orderby' => 'meta_value', 
                              'meta_key' => 'price' ) 
                     );

Which code should I use if also want to order by 'Size'?

Another example on which I need multiple sort on custom fields:

Display posts with 'Event' type ordered by 'Start_Hour' and then by 'Start_Minute'.

like image 426
Alex Avatar asked Oct 01 '12 19:10

Alex


2 Answers

Thanks to Bainternet I found the solution:

function orderbyreplace($orderby) {
    return str_replace('menu_order', 'mt1.meta_value, mt2.meta_value', $orderby);
}

and...

$args = array(
  'post_type'=>'Events',
  'orderby' => 'menu_order',
  'order' => 'ASC',
  'meta_query' => array(
        array(
            'key' => 'Start_Hour',
            'value' => '',
            'compare' => 'LIKE'
        ),
        array(
            'key' => 'Start_Minute',
            'value' => '',
            'compare' => 'LIKE'
        )
    )
);

add_filter('posts_orderby','orderbyreplace');
$loop = new WP_Query( $args );
remove_filter('posts_orderby','orderbyreplace');
like image 141
Alex Avatar answered Oct 05 '22 14:10

Alex


I think this changed slightly in Wordpress 3.7.

I had to change

return str_replace('menu_order', 'mt2.meta_value, mt1.meta_value', $orderby);

into

return str_replace('wp_posts.menu_order', 'mt2.meta_value, mt1.meta_value', $orderby);

Thanks for the initial solution! [Edited]

like image 30
Chris Avatar answered Oct 05 '22 16:10

Chris