使用 wc_price WooCommerce 挂钩时遇到格式不正确的数值

A non well formed numeric value encountered while using wc_price WooCommerce hook

我有一个简单的功能,几年前我在某个地方上网时曾经使用过。它允许我手动更改 EUR(€,欧元)的货币兑换率。

现在的问题是:

Notice: A non well formed numeric value encountered in /wp-content/themes/theme/functions.php on line 82

其中通知是指这一行:

$new_price = $price * $conversion_rate;

这就是我需要帮助解决的问题。

这是完整的代码:

function manual_currency_conversion( $price ) {

    $conversion_rate = 1.25;

    $new_price = $price * $conversion_rate;

    return number_format( $new_price, 2, '.', '' );
}

add_filter( 'wc_price', 'manual_currency_conversion_display', 10, 3 );
function manual_currency_conversion_display( $formatted_price, $price, $args ) {

    $price_new = manual_currency_conversion( $price );

    $currency = 'EUR';

    $currency_symbol = get_woocommerce_currency_symbol( $currency );

    $price_new = $currency_symbol . $price_new;

    $formatted_price_new = "<span class='price-new'> ($price_new)</span>";

        return $formatted_price . $formatted_price_new;
}
  • 自 WooCommerce 3.2.0 起,wc_price 过滤器挂钩包含 4 个参数,甚至包含 5 个来自 WooCommerce 5.0.0

  • 第二个参数$price,是一个字符串。因此,您收到错误消息是因为您正在使用它进行计算。解决方案是将其转换为 float

所以你得到:

function manual_currency_conversion( $price ) { 
    $conversion_rate = (float) 1.25;
    
    $new_price = (float) $price * $conversion_rate;

    return number_format( $new_price, 2, '.', '' );
}
 
/**
 * Filters the string of price markup.
 *
 * @param string       $return            Price HTML markup.
 * @param string       $price             Formatted price.
 * @param array        $args              Pass on the args.
 * @param float        $unformatted_price Price as float to allow plugins custom formatting. Since 3.2.0.
 * @param float|string $original_price    Original price as float, or empty string. Since 5.0.0.
 */
function filter_wc_price( $return, $price, $args, $unformatted_price, $original_price = null ) {
    // Call function
    $price_new = manual_currency_conversion( $price );

    $currency = 'EUR';

    $currency_symbol = get_woocommerce_currency_symbol( $currency );

    $price_new = $currency_symbol . $price_new;

    $formatted_price_new = "<span class='price-new'> ($price_new) </span>";

    return $return . $formatted_price_new;
}
add_filter( 'wc_price', 'filter_wc_price', 10, 5 );