How to sort multiple wordpress custom field values

2019-03-16 16:24发布

问题:

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

回答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.