Rav*_*rma 2 php wordpress cart woocommerce hook-woocommerce
我想在 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.
}
}
Run Code Online (Sandbox Code Playgroud)
You are using the right hook and here is the functional and tested code for Woocommerce version 2.6x to 3.0+, that is going to do the trick (instead you can make your calculation on cart items, and you will get the same thing) :
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+
}
}
}
Run Code Online (Sandbox Code Playgroud)
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
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.
You can see it trying this working code for WooCommerce version 2.6.x and 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;
}
Run Code Online (Sandbox Code Playgroud)
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
| 归档时间: |
|
| 查看次数: |
14062 次 |
| 最近记录: |