有时您可能需要为您的价格添加前缀或后缀。它可能是 “从…”,“只有”,“免税” 等等。好消息是 – 这对 WooCommerce 过滤器非常简单(记住,过滤器会更改现有变量的值 ; 而操作添加内容)。
目标:为 WooCommerce 价格添加前缀和后缀

PHP Snippet 1:为 WooCommerce 价格添加前缀和后缀
/**
* @snippet Adds prefix and/or suffix to WooCommerce Prices
* @source https://businessbloomer.com/?p=472
* @author Rodolfo Melogli
* @compatible WooCommerce 2.4.7
*/
add_filter( 'woocommerce_get_price_html', 'bbloomer_price_prefix_suffix', 100, 2 );
function bbloomer_price_prefix_suffix( $price, $product ){
$price = 'prefix here ' . $price . ' suffix here';
return apply_filters( 'woocommerce_get_price', $price );
}
PHP Snippet 2(替代):为 WooCommerce 价格添加前缀和后缀
/**
* @snippet Adds prefix and/or suffix (if tax enabled) to WooCommerce Prices
* @source https://businessbloomer.com/?p=472
* @author Rodolfo Melogli
* @compatible WooCommerce 2.4.7
*/
add_filter( 'woocommerce_get_price_html', 'bbloomer_price_prefix_suffix', 100, 2 );
function bbloomer_price_prefix_suffix( $price, $product ){
// To add suffix, go to /wp-admin/admin.php?page=wc-settings&tab=tax
$price = 'prefix here ' . $price . $product->get_price_suffix();
return apply_filters( 'woocommerce_get_price', $price );
}
PHP Snippet 3:只为一个类别添加前缀和后缀 WooCommerce 价格
/**
* @snippet Adds prefix and/or suffix to WooCommerce Prices (conditionally per category)
* @source https://businessbloomer.com/?p=472
* @author Rodolfo Melogli
* @compatible WooCommerce 2.4.7
*/
add_filter( 'woocommerce_get_price_html', 'bbloomer_price_prefix_suffix', 100, 2 );
function bbloomer_price_prefix_suffix( $price, $product ){
// change 'audio' with your the category slug
if ( has_term( 'audio', 'product_cat' ) ) {
$price = 'prefix here ' . $price . ' suffix here';
}
// no need to put the else! $price will stay the same
return apply_filters( 'woocommerce_get_price', $price );
}
可以在哪里添加此代码?
您可以将 PHP 代码片段放置在主题或子主题的 functions.php 文件的底部(如果是 CSS 代码,请添加到主题的 style.css 文件底部),修改之前建议先备份原始文件,若出现错误请先删除此代码。
这段代码是否正常可用?
或者是您有更好的解决方案想要分享?请到薇晓朵 WooCommerce 中文论坛留言告知,我们希望可以帮到更多国内的 WooCommerce 用户也希望您的参与。
需要关于 WooCommerce 的帮助?
请观看我们提供的免费视频教程或到薇晓朵 WooCommerce 中文论坛提问,会有专业技术团队提供相关帮助。