通过挂钩更改产品价格的问题

时间:2020-02-25 08:15:39

标签: php wordpress woocommerce

我有一家基于Woocommerce的商店。 我使用This Link通过LoicTheAztec的钩子来更改商品价格。

它工作正常,但是我发现当用户打开产品页面或任何包含价格的页面时,它将给出错误消息(存储在错误日志文件中,用户看不到)。

均值错误以调试模式显示,并且也存储在Root的error_log文件中。

错误:[25-Feb-2020 11:12:57 ...] PHP警告:在/home/website/public_html/wp-content/themes/name/functions.php中遇到的非数字值1147

Line 1147: return $price * get_price_multiplier();

使用此钩子:

// Utility function to change the prices with a multiplier (number)
function get_price_multiplier() {
    return 1.2; // x2 for testing
}

// Simple, grouped and external products
add_filter('woocommerce_product_get_price', 'custom_price', 99, 2 );
add_filter('woocommerce_product_get_regular_price', 'custom_price', 99, 2 );
// Variations
add_filter('woocommerce_product_variation_get_regular_price', 'custom_price', 99, 2 );
add_filter('woocommerce_product_variation_get_price', 'custom_price', 99, 2 );
function custom_price( $price, $product ) {
    return $price * get_price_multiplier();
}

// Variable (price range)
add_filter('woocommerce_variation_prices_price', 'custom_variable_price', 99, 3 );
add_filter('woocommerce_variation_prices_regular_price', 'custom_variable_price', 99, 3 );
function custom_variable_price( $price, $variation, $product ) {
    // Delete product cached price  (if needed)
    // wc_delete_product_transients($variation->get_id());

    return $price * get_price_multiplier();
}

// Handling price caching (see explanations at the end)
add_filter( 'woocommerce_get_variation_prices_hash', 'add_price_multiplier_to_variation_prices_hash', 99, 1 );
function add_price_multiplier_to_variation_prices_hash( $hash ) {
    $hash[] = get_price_multiplier();
    return $hash;
}
  • Woocommerce版本:3.9.2
  • PHP版本:7.2

1 个答案:

答案 0 :(得分:1)

返回之前,您可以将$price转换为数值。

$price = (float)$price;