问题
I'm trying to change the cart totals with code but I don't know how. I have managed to change the price for each item in the cart using the filter woocommerce_cart_item_price
. Is there such a filter for the cart totals(see arrow in picture)?
This is the code for each individual item:
add_filter( 'woocommerce_cart_item_price', 'func_change_product_price_cart', 10, 3 );
function func_change_product_price_cart($price, $cart_item, $cart_item_key){
if ( isset($cart_item['tau_lengde']) ) {
if ( WC()->cart->display_prices_including_tax() ) {
$product_price = wc_get_price_including_tax( $cart_item['data'] );
} else {
$product_price = wc_get_price_excluding_tax( $cart_item['data'] );
}
$price = wc_price( (($product_price * $cart_item['tau_lengde']) + $cart_item['price_one_end'] + $cart_item['price_other_end']));
return $price;
}
}
回答1:
add_filter( 'woocommerce_cart_total', 'wc_modify_cart_price' );
function wc_modify_cart_price( $price ) {
$addition = 10;
return $price+addition;
}
Here
add_filter( 'woocommerce_calculated_total', 'modify_calculated_total', 20, 2 );
function modify_calculated_total( $total, $cart ) {
return $total + 10;
}
Item total = A fixed amount * Quantity
add_action( 'woocommerce_before_calculate_totals', 'modify_cart_price', 20, 1);
function modify_cart_price( $cart_obj ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) || ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ))
return;
foreach ( $cart_obj->get_cart() as $cart_item ) {
$cart_item['data']->set_price( 1000);
}
}
Item total = Item price * Quantity ( Default )
add_action( 'woocommerce_before_calculate_totals', 'modify_cart_price', 20, 1);
function modify_cart_price( $cart_obj ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) || ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ))
return;
foreach ( $cart_obj->get_cart() as $cart_item ) {
$cart_item['data']->set_price( $cart_item['data']->get_price());
}
}
Product subtotal in cart
function filter_woocommerce_cart_product_subtotal( $product_subtotal, $product, $quantity, $instance ) {
$product_subtotal = $product->get_price()*$quantity;
return $product_subtotal;
};
add_filter( 'woocommerce_cart_product_subtotal', 'filter_woocommerce_cart_product_subtotal', 10, 4 );
来源:https://stackoverflow.com/questions/55178683/woocommerce-modify-cart-totals-programmatically