Order wp query posts by custom order calculated from post meta value


I am using wordpress REST API to query the database.
For each product (a custom post) I have a meta which is product_price at a certain currency currency_rate.
I need to run a query to get all products ordered ASC or DESC depending on product_price . However, since each price is at a different currency, the query needs first to convert all prices to a common currency, then sort them by the chosen order. I am not able to do it.
I found this link
wordpress orderby filter but I couldn’t understand how to use it. The documentation is not clear at all for me. I need to modify the ordering by something similar to the below

$args = array(
        'post_type' => 'product',
        'meta_key' => 'product_price',
        'orderby'   => 'meta_value_num',
        'order' => 'ASC'
$q = new WP_Query($args);

add_filter( 'posts_orderby', 'filter_query',10,2 );

function filter_query($orderby_statement, $wp_query) {
    $orderby_new_statement = 'product_price*currency_rate ASC';
    return $orderby_new_statement;

What I need to do is to multiply each price by a conversion rate and feed that into the query to give me the posts in the correct order. I am currently stuck. Thanks for your help.

, , , houssameddin 1 year 2020-07-14T19:10:59-05:00 0 Answers 67 views 0

Leave an answer