将折扣百分比添加到 Woocommerce 中的可变产品价格范围

问题描述 投票:0回答:1

使用 Woocommerce,我已使用以下代码成功从产品档案页面中删除了销售徽章和价格:

// Remove Sales Flash
add_filter('woocommerce_sale_flash', 'woo_custom_hide_sales_flash');
function woo_custom_hide_sales_flash()
{
    return false;
}

// Remove prices on archives pages
remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10 );

所有产品均为可变产品,所有变体价格相同。而且实际上所有价格都是促销价。

我想在每个可变价格范围后添加折扣百分比,在单个产品页面。我尝试过使用以下代码:

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 . '%' );
}

但我什么也没得到

我做错了什么,该怎么办?

对此的任何帮助将不胜感激。

php wordpress woocommerce formatting product-price
1个回答
5
投票

我一直在测试代码,当您的目标是可变产品的销售价格范围时,最好在位于

woocommerce_format_sale_price
函数中的
wc_format_sale_price()
过滤器挂钩中使用自定义挂钩函数。

当所有变体具有相同价格时,这将允许在价格范围后显示保存的折扣百分比。如果变体价格不同,则该百分比只会出现在变体价格上。

所以我重新审视了你的代码:

// Removing sale badge
add_filter('woocommerce_sale_flash', '__return_false');

// Removing archives prices
remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10 );

// Add the saved discounted percentage to variable products
add_filter('woocommerce_format_sale_price', 'add_sale_price_percentage', 20, 3 );
function add_sale_price_percentage( $price, $regular_price, $sale_price ){
    // Strip html tags and currency (we keep only the float number)
    $regular_price = strip_tags( $regular_price );
    $regular_price = (float) preg_replace('/[^0-9.]+/', '', $regular_price);
    $sale_price = strip_tags( $sale_price );
    $sale_price = (float) preg_replace('/[^0-9.]+/', '', $sale_price);

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

    // return on sale price range with "Save " and the discounted percentage
    return $price . ' <span class="save-percent">' . $percentage . '%</span>';
}

代码位于活动子主题(活动主题)的 function.php 文件中。

已测试且有效。

© www.soinside.com 2019 - 2024. All rights reserved.