2017-05-03 74 views
6

折扣百分比我在主题展示后价格的百分比function.php有这个代码,它是在WooCommerce v2.6.14工作的罚款。显示附近销售价格在单品页WC 3.0+

但这个片段已经不上WooCommerce 3.0或更高版本的工作。

我该如何解决这个问题?

下面是代码:

// Add save percent next to sale item prices. 
add_filter('woocommerce_sale_price_html', 'woocommerce_custom_sales_price', 10, 2); 
function woocommerce_custom_sales_price($price, $product) { 
    $percentage = round((($product->regular_price - $product->sale_price)/$product->regular_price) * 100); 
    return $price . sprintf(__(' Save %s', 'woocommerce'), $percentage . '%'); 
} 

回答

8

woocommerce_sale_price_html已经WooCommerce 3.0+被替换为不同的钩,其具有现在3个参数(但不是$product论点了)。

这里是一个功能类似的代码:

// Only for WooCommerce version 3.0+ 
add_filter('woocommerce_format_sale_price', 'woocommerce_custom_sales_price', 10, 3); 
function woocommerce_custom_sales_price($price, $regular_price, $sale_price) { 
    $percentage = round(($regular_price - $sale_price)/$regular_price * 100).'%'; 
    $percentage_txt = __(' Save ', 'woocommerce').$percentage; 
    $price = '<del>' . (is_numeric($regular_price) ? wc_price($regular_price) : $regular_price) . '</del> <ins>' . (is_numeric($sale_price) ? wc_price($sale_price) . $percentage_txt : $sale_price . $percentage_txt) . '</ins>'; 
    return $price; 
} 

此代码放在你的活跃儿童主题(或主题)的function.php文件或也以任何插件文件。

此代码测试,只为WooCommerce 3.0以上版本


更新工程,以避免NAN%百分比值时经常和销售价格是HTML预格式化:

add_filter('woocommerce_format_sale_price', 'woocommerce_custom_sales_price', 10, 3); 
function woocommerce_custom_sales_price($price, $regular_price, $sale_price) { 
    // Getting the clean numeric prices (without html and currency) 
    $regular_price = floatval(strip_tags($regular_price)); 
    $sale_price = floatval(strip_tags($sale_price)); 

    // Percentage calculation and text 
    $percentage = round(($regular_price - $sale_price)/$regular_price * 100).'%'; 
    $percentage_txt = __(' Save ', 'woocommerce').$percentage; 

    return '<del>' . wc_price($regular_price) . '</del> <ins>' . wc_price($sale_price) . $percentage_txt . '</ins>'; 
} 

此代码放在你的活跃儿童主题(或主题)的function.php文件或也以任何插件文件中。

此代码测试,仅适用于WooCommerce 3.0以上版本(感谢@AsifRao)

+0

真棒,它的工作原理! – decupe

+0

其返回的NAN% –

+0

@LoicTheAztec在我的情况下$ regular_price returrning 65.99 $“不仅仅是正常价格但是这一切的HTML和这就是为什么它返回南 –

相关问题