WordPress order posts by 2 custom fields at once

Viewed 408

I want to order the posts by 2 custom fields in the same call. How is this possible?

This next code order successfully, but only by only 1 NUMBER custom field (not STRING):

add_action('pre_get_posts', function ($q) {
    if (
        !is_admin() // Target only front end queries
        && $q->is_main_query() // Target the main query only
        && ($q->is_search() || $q->is_post_type_archive('data-base'))
    ) {
        $q->set('meta_key', 'custom_field_1');
        $q->set('order',    'DESC');
        $q->set('orderby',  'meta_value');
    }
});

Update 1:

Currently @Mohammed Yassine CHABLI's first answer works, but it doesn't sort by number, but by String. That means that "81" will come before "9", which is not good. Any solution for that?


Resources that might help:

a more powerful order by in WordPress 4.0

Add meta_type in custom sorting using woocommerce

3 Answers

You need the WP way of providing an expression in the ORDER BY;

ORDER BY 0 + meta_key

That is, do something to meta_key to convert it into a numeric value.

Try this one :

configure the meta query :

$meta_query = array(
    'relation' => 'AND',
    'clause1' => array(
        'key'     => 'first key of your meta',
        'compare' => 'EXISTS',
    ),
    'clause2' => array(
        'key'     => 'second key of your meta',
        'compare' => 'EXISTS',
    ));

$q->set('meta_query', $meta_query);


$q->set('orderby',array( 
   'clause1'  => 'DESC', 
   'clause2'  => 'ASC' 
      )  
);

In case you want to sort in the same direction :

$q->set('orderby' =>'clause1 clause2',
        'order'   =>'ASC'
);

A possible simple solution would be to format the text as if it were a number.

ORDER BY LPAD(meta_key, 5, '0')

Samples:

 9 = 00009
 81 = 00081
 777 = 00777

The weight on the performance of the query is to be evaluated.

Related