php 价格显示,php - 在WC 3.0+的“变化产品”页面中,按正常价格和销售价格显示折扣百分比[重复] - 堆栈内存溢出...

博主分享了在 WooCommerce 中遇到的价格显示和折扣百分比计算错误的问题。通过研究和调整代码,最终找到了解决方案。代码修改涉及价格的格式化,以正确显示带有小数点的百分比,并确保折扣计算准确。更新后的代码成功地在产品页面上显示了最高折扣百分比。
摘要由CSDN通过智能技术生成

我想显示价格(正常价格和销售价格)下的折扣销售百分比。

帖子中有一个非常接近的解决方案:

但是问题在于它改变了价格。 在代码显示如下之前:

c689e036517d8c962307cfa521d3fa94.png

在这样的代码之后:

89b6c0e6ab852b67250440f58d236f21.png

如您所见,小数点消失了并且百分比不正确,因为它应该显示15%价格55€-15%折扣-> 46,75€

使用的代码:

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 '' . wc_price( $regular_price ) . ' ' . wc_price( $sale_price ) . $percentage_txt . '';

}

我的预期结果将是这样,但找不到解决方法。

25f97183ec1a9e5494e1ab35b1b9eda8.png

我已经阅读了很多有关它的文章,但是找不到正确的解决方案。 如果我重复此帖子,我深表歉意。 谢谢

更新于08/24/2019解决

经过对这些网站的一些研究,我终于解决了这个问题,并得到了想要的结果。 我在这里留下了我使用的代码,因此任何人都可以使用它。

add_action( 'woocommerce_single_product_summary',

'porcentaje_ahorro_ficha_producto', 12 );

function porcentaje_ahorro_ficha_producto() {

global $product;

if ( ! $product->is_on_sale() ) return;

if ( $product->is_type( 'simple' ) ) {

$max_percentage = ( ( $product->get_regular_price() - $product-

>get_sale_price() ) / $product->get_regular_price() ) * 100;

} elseif ( $product->is_type( 'variable' ) ) {

$max_percentage = 0;

foreach ( $product->get_children() as $child_id ) {

$variation = wc_get_product( $child_id );

$price = $variation->get_regular_price();

$sale = $variation->get_sale_price();

if ( $price != 0 && ! empty( $sale ) ) {

$percentage = ( $price - $sale ) / $price * 100;

}

if ( $percentage > $max_percentage ) {

$max_percentage = $percentage;

}

}

}

if ( $max_percentage > 0 ) echo "

-" .

round($max_percentage) . "%

";

}

然后我做了一些CSS,仅此而已。 谢谢大家的支持。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值