0

I can use orderby with one meta key in the WP_Query using following:

'orderby'   => 'meta_value_num',
'meta_key'  => 'my_key_1',

However is it possible to use orderby based on the calculation of 2 meta fields?

For example I have two meta fields my_key_1 and my_key_2. I want to divide the value key 1 by 2 and orderby that result. Something like

meta_key = my_key_1/my_key_2
0

One of the options would be to sort at a database level by a dynamically calculated column. This is too complex for me.

Having your task on production I would probably create a third meta key: 'division' derivated from the two and update its value on every post save. Then I would sort by this key in WP_Query().

Third option for small amount of posts would be to sort an array.

Define helper fuction:

function sort_by_division( $posts ) {
  foreach ( $posts as $i => $post ) :
    $my_key_1 = (float)get_post_meta( $post->ID, 'my_key_1', true );
    $my_key_2 = (float)get_post_meta( $post->ID, 'my_key_2', true ); 
    $division = $my_key_1 / $my_key_2;
    $divisions[$i] = $division;
  endforeach;
  array_multisort( $divisions, SORT_DESC, $posts );
  return $posts;
}

And apply it for the results of the query:

<?php $myposts = sort_by_division( get_posts() ); ?>
<ul>
<?php
foreach ( $myposts as $post ) : setup_postdata( $post ); 
  $my_key_1 = (float)get_post_meta( $post->ID, 'my_key_1', true );
  $my_key_2 = (float)get_post_meta( $post->ID, 'my_key_2', true ); 
  $division = $my_key_1 / $my_key_2;
  ?>
  <li>
    <?php the_title(); ?><br>
    my_key_1: <?php echo $my_key_1; ?><br>
    my_key_2: <?php echo $my_key_2; ?><br>
    division: <?php echo $division; ?>
  </li>
<?php endforeach;
wp_reset_postdata();?>
</ul>

As I said, not usable for large amount of posts because of memory consumption. An option with third meta key is most efficient.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.