【发布时间】:2019-12-25 14:26:45
【问题描述】:
我想在价格(正常价格和促销价)下显示折扣销售百分比。
帖子中有一个非常接近的解决方案:
Display the discounted percentage near sale price in Single product pages for WC 3.0+
但问题是它会改变价格。 在代码出现之前是这样的:
在这样的代码之后:
你可以看到小数消失了,百分比不正确,因为它应该显示 15% Price 55€-15% off --> 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 '<del>' . wc_price( $regular_price ) . '</del> <ins>' . wc_price( $sale_price ) . $percentage_txt . '</ins>';
}
我的预期结果会是这样,但找不到方法。
我已经阅读了很多关于它的帖子,但找不到正确的解决方案。如果我复制该帖子,我深表歉意。谢谢
2019 年 8 月 24 日更新已解决
在对她的网站进行一些研究后,我终于解决了问题并得到了我想要的结果。我把我使用的代码留在这里,这样任何人都可以使用它。
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 "<div class='porcentaje-ahorro'>-" .
round($max_percentage) . "%</div>";
}
然后我做了一些 css,仅此而已。谢谢大家的支持。
【问题讨论】:
-
我有updated my answer code 以避免您报告的舍入问题。现在要获得您想要的输出,您需要使用另一个钩子并进行更多搜索……
-
谢谢@LoicTheAztec!现在价格以小数显示!,我唯一不明白的是显示的百分比,它显示 16% 但它显示 15% .. percentage 我不能在另一个问题上发帖,因为我是新人所以在这里发表评论。
-
抱歉,代码现在可以正常工作了……我已经用硬编码的价格进行了测试:
$regular_price = 55;和$sale_price = 46.75;……我得到了15%但不像以前那样16%! ……请参阅this screenshot 作为证明……因此,您的情况还有其他问题,没有人能提供更多帮助。 -
非常感谢!我真的很感激!
-
请不要用解决方案编辑您的问题,而是为您自己的问题创建一个答案。
标签: php wordpress woocommerce price discount