自定义产品销售闪存徽章

时间:2017-03-19 07:14:34

标签: php wordpress woocommerce product badge

我正在尝试使用此处的代码段在销售闪存徽章上添加总金额,但由于它无法正常运行,因此出现了问题。 任何建议都会非常感激。

// 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 );
}

由于

1 个答案:

答案 0 :(得分:2)

  

添加了WC 3+兼容性

您的过滤器中没有正确的参数(例如, $price 不存在),请参阅此处{{3}的相关源代码过滤器钩子以便更好地理解:

/* 
 *  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文件中,或者放在任何插件文件中。

此代码经过测试并有效。

相关问题