Customizing the product sale flash badge

送分小仙女□ 提交于 2019-12-02 06:36:00

问题


I am trying to add save amount total on the sale flash badge using this snippet here below but there is something wrong since it is not working. Any advice would be really appreciated.

// 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


回答1:


Added WC 3+ compatibility

You don't have the correct arguments in your filter ($price doesn't exist for example), see here the related source code for woocommerce_sale_flash filter hook to understand better:

/* 
 *  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 ); ?>

So your working code is going to be something like:

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

The Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works.



来源:https://stackoverflow.com/questions/42883944/customizing-the-product-sale-flash-badge

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!