自定义产品销售 Flash 徽章

2023-12-13

我正在尝试使用下面的此代码片段在销售闪存徽章上添加节省总额,但由于它不起作用而出现问题。 任何建议将不胜感激。

// Add save amount on the sale badge.
add_filter( 'woocommerce_sale_flash', 'woocommerce_custom_badge', 10, 2 );
function woocommerce_custom_badge( $price, $product ) {
$saved = wc_price( $product->regular_price - $product->sale_price );
return $price . sprintf( __(' <div class="savings">Save %s</div>', 'woocommerce' ), $saved );
}

Thanks


添加了 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 文件中或任何插件文件中。

这段代码已经过测试并且可以工作。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

自定义产品销售 Flash 徽章 的相关文章

随机推荐