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’?

Read More

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’.

Related posts

Leave a Reply

4 comments

  1. 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');
    
  2. 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]

  3. Here’s an example of using more than one meta_key and orderby that I believe should work:

    $params = array(
    'post_type' => 'product',
    'meta_query' => array(
        array(
                'key' => 'price',
                'value' => '',
                'compare' => 'LIKE'
        ),
        array(
                'key' => 'size',
                'value' => '',
                'compare' => 'LIKE'
        )
    ),
    'orderby' => 'price size',
    'order' => 'ASC'
    );
    $query = new WP_Query;
    $resulting_obj = $query->query($params);
    

    You’ll need to play with the meta_query items a bit more, especially the ‘value’ parameter. Please have a good look at http://codex.wordpress.org/Class_Reference/WP_Query in the ‘Custom Field Parameters’ section.

  4. You don’t need any filter or hooks to sort multiple custom fields, if your one of custom field is meta_key and other one is normal column of table, than use these parameters/arguments in your query.

    'meta_key' => 'KEY_NAME',
    'orderby' => 'meta_value_num SECOND_COLUMN_NAME',
    'order' => 'ASC' or 'order' => 'DESC'
    

    Here the order of meta_value_num and SECOND_COLUMN_NAME matter, you may see different-2 result based on the order.