自定义产品销售闪光徽章 [英] Customizing the product sale flash badge

查看:47
本文介绍了自定义产品销售闪光徽章的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用下面的此代码段在销售闪存徽章上添加总储蓄金额,但由于无法正常工作,因此出现问题.任何建议将不胜感激.

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

谢谢

推荐答案

添加了 WC 3+ 兼容性

Added WC 3+ compatibility

您的过滤器中没有正确的参数(例如,$price 不存在),请参阅此处 woocommerce_sale_flash 过滤钩子以更好地理解:

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

代码位于活动子主题(或主题)的 function.php 文件或任何插件文件中.

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.

这篇关于自定义产品销售闪光徽章的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆