我想更新 WooCommerce 中的购物车小计。
如何在 WooCommerce 中添加修改小计的操作?
我尝试过这段代码,但不起作用。我想将购物车小计乘以 12 并在购物车页面上显示此计算结果。
这是我的代码:
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
function add_custom_price( $total) {
foreach ( $total->cart_contents as $key => $value ) {
$modifiedtotal = $total->subtotal * 12;
// --------------------------------
//how can get subtotal with multiply by 12 and it should be show on cart page.
}
}
最佳答案
您使用的是正确的钩子(Hook),这里是 Woocommerce 版本 2.6x 到 3.0+ 的功能和测试代码,这将解决问题(相反,您可以对购物车项目进行计算,您将得到同样的东西):
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 10, 1);
function add_custom_price( $cart_object ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
foreach ( $cart_object->get_cart() as $cart_item ) {
## Price calculation ##
$price = $cart_item['data']->price * 12;
## Set the price with WooCommerce compatibility ##
if ( version_compare( WC_VERSION, '3.0', '<' ) ) {
$cart_item['data']->price = $price; // Before WC 3.0
} else {
$cart_item['data']->set_price( $price ); // WC 3.0+
}
}
}
代码位于事件子主题(或主题)的 function.php 文件中或任何插件文件中。
Explanations:
Using a calculation based on the cart subtotal, will only display the calculation on subtotal cart line row, without updating the cart items, the cart items line subtotals, and the cart total.
您可以看到它正在尝试 WooCommerce 版本 2.6.x 和 3.0+ 的工作代码:
add_action( 'woocommerce_calculate_totals', 'add_custom_price', 10, 1);
function add_custom_price( $cart_object ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_calculate_totals' ) >= 2 )
return;
$cart_object->subtotal *= 12;
}
代码位于事件子主题(或主题)的 function.php 文件中或任何插件文件中。
关于php - 更新 WooCommerce 中的购物车小计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43915159/