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

给你一囗甜甜゛ 提交于 2021-02-10 17:38:04

问题


I have a simple function that used to work that I got online somewhere a few years back. It allows me to manually change the currency conversion rate for EUR (€, Euro).

Problem now is this:

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

Whereof the notice refers to this line:

$new_price = $price * $conversion_rate;

This is what I need help fixing.

This is the complete code:

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;
}

回答1:


  • Since WooCommerce 3.2.0 the wc_price filter hook contains 4 params and even 5 from WooCommerce 5.0.0

  • The 2nd param $price, is a string. Hence the error message you get because you are doing calculations with it. The solution is to convert this to a float

So you get:

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 );


来源:https://stackoverflow.com/questions/66084833/a-non-well-formed-numeric-value-encountered-while-using-wc-price-woocommerce-hoo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!