Additional price based on cart item count in WooCommerce(基于 WooCommerce 中购物车项目数量的附加价格)
问题描述
基于"woocommerce 在结帐和购物车中更改价格页面" 回答更改结帐页面总价的代码,我添加了一些额外的代码来计算用户在购物车中拥有的产品,如果用户在购物车中有 9 个产品,则添加一些价格总计:
Based on "woocommerce change price in checkout and cart page" answer code that change the total price in checkout page, I have added some extra code to count the products that user have in cart and if user had like 9 products in cart then add some price to total:
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;
}
}
但它不起作用.这张图片将说明一切:
如果有人可以更正代码并告诉我如何显示图片中的消息,我将不胜感激
I will appreciate if anyone could correct the code and tell me how can I display the message like in the picture
推荐答案
你最好改用 FEE API,这样:
You should better use the FEE API instead, this way:
// 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 文件中.经测试有效.
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
如果您想为包装费启用税金,请将第三个参数从 false
更改为 true
.
If you want to enable taxes for the packing fee, change the third argument from
false
totrue
.
这篇关于基于 WooCommerce 中购物车项目数量的附加价格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:基于 WooCommerce 中购物车项目数量的附加价格
基础教程推荐
- Libpuzzle 索引数百万张图片? 2022-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 在多维数组中查找最大值 2021-01-01