php - 基于 WooCommerce 中购物车商品数量的额外价格
问题描述
基于“结帐和购物车页面中的 woocommerce 更改价格”答案代码更改结帐页面中的总价,我添加了一些额外的代码来计算用户在购物车中拥有的产品,如果用户在购物车中有 9 种产品然后添加一些总价:
add_action( 'woocommerce_before_cart_totals', 'custom_cart_total' , 'get_cart_contents_count');
function custom_cart_total() {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if (WC()->cart->get_cart_contents_count() == 9){
WC()->cart->total += 15;
}
elseif(WC()->cart->get_cart_contents_count() == 6){
WC()->cart->total += 14;
}
elseif(WC()->cart->get_cart_contents_count() == 4){
WC()->cart->total += 13;
}
}
但它不起作用。这张图片将解释一切:
如果有人可以更正代码并告诉我如何显示图片中的消息,我将不胜感激
解决方案
您应该更好地使用 FEE API,这样:
// Add a custom packing fee based on item count
add_action( 'woocommerce_cart_calculate_fees', 'custom_packing_fee', 10, 1 );
function custom_packing_fee( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_cart_calculate_fees' ) >= 2 )
return;
$count = $cart->get_cart_contents_count();
if ( $count >= 9 ){
$fee = 15;
}
elseif( $count >= 6 && $count < 9 ){
$fee = 14;
}
elseif( $count >= 4 && $count < 6 ){
$fee = 13;
}
if ( isset($fee) && $fee > 0 ) {
$label = sprintf( __('Box fee (%d items)'), $count);
$cart->add_fee( $label, $fee, false );
}
}
代码在您的活动子主题(或活动主题)的 functions.php 文件中。测试和工作。
如果要为包装费启用税费,请将第三个参数从 更改
false
为true
。
推荐阅读
- python - 在pyqt5中单击登录按钮时获取小部件未定义错误
- fiware - Fiware Orion 代理和数据库连接
- javascript - 使用 ajax 和 django 框架重新加载 div 并显示 json
- javascript - Fontawesome 将节点转换为 SVG(主动)
- linux - 在 X86 上的 Linux 中如何共享 PMU?
- c# - 如何将自定义 TokenFilter 从 Lucene.Net 3.0.3 迁移到 4.8
- r - 我们不能将管道链输出传递给线性模型 lm() 点占位符吗?
- flutter - 在 Flutter 中与 TextFormField 一起使用时未显示 showdialog
- java - 即使我可以从命令行连接,也无法从 Gradle 连接到远程 MongoDB
- php - 如何循环表格行和列