I’m trying to build a custom query that’s a combination of custom key values. For example, with the code below I’m able to sort my posts by how much money they’ve received (paidusd) and how much tips they’ve received (totaltips). This code is working great.
But what I’d like to do is add another sort for “most profitable” which would be the ratio of paidusd to totaltips. Where would I perform that division equation? I’m stumped.
Any help is greatly appreciated – thanks!!!!
if ( $_GET['sort'] == 'mostexpensive'){
//query_posts('&meta_key=paidbtc&orderby=meta_value');
$args = array(
'meta_key' => 'paidusd',
'orderby' => 'meta_value',
'posts_per_page' => 10,
'paged' => $paged
);
query_posts($args);
}
if ( $_GET['sort'] == 'mosttipped'){
$args = array(
'meta_key' => 'totaltips',
'orderby' => 'meta_value',
'posts_per_page' => 10,
'paged' => $paged
);
query_posts($args);
}
What you are wanting to do is possible– MySQL can do math– but
WP_Query
can’t handle this natively. You’d need to apply a filter or two. You would end up sorting on generated values which is not especially efficient. That is, MySQL, would read all of the rows in the table for those two keys, do some math, and then sort.My advice would be to store a third key– say,
profitability
— when you save the post keys, and then sort on that instead of trying to generate this is SQL. Something, very crudely, like this: