我也有这样的情况。我正在建立一个 WordPress 网站来销售一些产品。问题是产品的价格存储为元值,但产品价格可以采用不同的货币。现在的问题是,我必须为所有产品制作一个价格过滤器,无论价格是什么货币,过滤器货币是在后台配置的,并且没有该货币价格的产品必须是按货币兑换税过滤,但我真的不知道如何构建元查询,以便我可以按货币等价价格过滤。
例如我有这2个产品:
产品1 -价格:10 -货币:美元
产品2 - 价格:1000 - 货币:xxx
过滤器设置为使用 usd 并查找 0 到 10 之间的价格。因此,这次搜索将返回 product 1,但从 xxx 到 usd 的货币换算为 500 比 1,产品 2 等值价格为 2 美元,它必须包含在搜索结果中。
到目前为止,这是我处理价格过滤器的代码部分:
if (
isset($_REQUEST['max_price']) && $_REQUEST['max_price'] &&
isset($_REQUEST['min_price']) && ($_REQUEST['min_price'] || $_REQUEST['min_price'] == 0)
) {
$main_currency = cs_get_option('main_currency');
$ex_currency = array_diff(['xxx', 'usd'], [$main_currency])[1];
$args['meta_query'] [] =
array(
'relation' => 'AND',
array(
'key' => 'price_meta_key',
'value' => array($_REQUEST['min_price'], $_REQUEST['max_price']),
'type' => 'numeric',
'compare' => 'BETWEEN',
),
array(
'key' => 'product_currency',
'value' => $main_currency,
'compare' => '='
)
);
}
但这只会过滤具有 $main_currency 货币的产品。
您可以建立匹配多种货币的查询:
// Define currencies and exchange rates
$currencies = array(
'usd' => 1,
'eur' => 0.86
);
// Generate a term for each currency
$terms = array();
foreach ($currencies as $currency => $rate) {
// Match the currency code and the converted price range
$terms[] = array(
'relation' => 'AND',
array(
'key' => 'product_currency',
'value' => $currency
'compare' => '='
),
array(
'key' => 'price_meta_key',
'value' => array(
$_REQUEST['min_price'] * $rate,
$_REQUEST['max_price'] * $rate
),
'type' => 'numeric',
'compare' => 'BETWEEN'
)
);
}
// Finally OR the terms together
$args['meta_query'][] = array(
'relation' => 'OR',
$terms
);