Skip to content Skip to sidebar Skip to footer

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_act

Solution 1:

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

ORDERBY0 + meta_key

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

Solution 2:

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'
);

Solution 3:

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 = 0000981 = 00081777 = 00777

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

Post a Comment for "Wordpress Order Posts By 2 Custom Fields At Once"