添加了 WC 3+ 兼容性
您的过滤器中没有正确的参数($price
例如不存在),请参阅此处的相关源代码woocommerce_sale_flash过滤钩子以便更好地理解:
/*
* The filter hook woocommerce_sale_flash is located in:
* templates/loop/sale-flash.php and templates/single-product/sale-flash.php
*/
<?php if ( $product->is_on_sale() ) : ?>
<?php echo apply_filters( 'woocommerce_sale_flash', '<span class="onsale">' . esc_html__( 'Sale!', 'woocommerce' ) . '</span>', $post, $product ); ?>
所以你的工作代码将是这样的:
add_filter( 'woocommerce_sale_flash', 'woocommerce_custom_badge', 10, 3 );
function woocommerce_custom_badge( $output_html, $post, $product ) {
// Added compatibility with WC +3
$regular_price = method_exists( $product, 'get_regular_price' ) ? $product->get_regular_price() : $product->regular_price;
$sale_price = method_exists( $product, 'get_sale_price' ) ? $product->get_sale_price() : $product->sale_price;
$saved_price = wc_price( $regular_price - $sale_price );
$output_html = '<span class="onsale">' . esc_html__( 'Save', 'woocommerce' ) . ' ' . $saved_price . '</span>';
return $output_html;
}
该代码位于活动子主题(或主题)的 function.php 文件中或任何插件文件中。
这段代码已经过测试并且可以工作。