Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WordPress order posts by 2 custom fields at once

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

like image 597
Elron Avatar asked May 03 '26 21:05

Elron


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

like image 187
Rick James Avatar answered May 06 '26 11:05

Rick James


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'
);
like image 29
Yassine CHABLI Avatar answered May 06 '26 10:05

Yassine CHABLI



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!