我遇到了与Woocommerce购物车总计仅显示添加到购物车的最后一件商品的价格有关的问题。单个项目的价格未正确总计到总价格,仅显示最后一个项目的价格。
这是我用来替代添加到购物车中的产品价格的代码:
function action_woocommerce_before_cart_table() {
global $woocommerce;
$items = $woocommerce->cart->get_cart();
foreach ($items as $item => $values) {
$price = 0;
if (array_key_exists('addons', $values) && count($values['addons']) > 0) {
foreach ($values['addons'] as $value) {
$price = $price + $value['price'];
}
} else {
$regular_price = get_post_meta($values['product_id'], '_regular_price', true);
$sale_price = get_post_meta($values['product_id'], '_sale_price', true);
$price = $regular_price;
}
$values['data']->set_price($price);
}
}
add_action('woocommerce_before_cart_table', 'action_woocommerce_before_cart_table', 10, 0);
function action_woocommerce_checkout_before_order_review() {
foreach (WC()->cart->get_cart() as $item => $values) {
$price = 0;
$quantity = $values['quantity'];
if (array_key_exists('addons', $values) && count($values['addons']) > 0) {
foreach ($values['addons'] as $value) {
$price = $price + $value['price'];
}
} else {
$regular_price = get_post_meta($values['product_id'], '_regular_price', true);
$sale_price = get_post_meta($values['product_id'], '_sale_price', true);
$price = $regular_price;
}
// $final_price = $quantity * $price;
$values['data']->set_price($price);
}
}
add_action('woocommerce_review_order_before_cart_contents', 'action_woocommerce_checkout_before_order_review', 10, 0);
function woocommerce_calculate_totals($cart) {
$cart_sub_total = 0;
global $woocommerce;
$items = $woocommerce->cart->get_cart();
foreach ($items as $item => $values) {
$price = 0;
$quantity = $values['quantity'];
if (array_key_exists('addons', $values) && count($values['addons']) > 1) {
foreach ($values['addons'] as $value) {
$price = $price + $value['price'];
}
} else {
$regular_price = get_post_meta($values['product_id'], '_regular_price', true);
$sale_price = get_post_meta($values['product_id'], '_sale_price', true);
$price = $regular_price;
}
$final_price = $quantity * $price;
$cart_sub_total = $final_price;
$values['data']->set_price($cart_sub_total);
}
WC()->cart->subtotal = $cart_sub_total;
$cart->sub_total = $cart_sub_total;
$coupons = WC()->cart->get_coupons();
$cupon_price = 0;
if (!empty($coupons)) {
foreach ($coupons as $code => $coupon) {
$cupon_price = $cupon_price + $coupon->get_amount();
}
}
$new_price = $cart_sub_total - $cupon_price;
WC()->cart->total = $new_price;
$cart->total = $new_price;
}
add_action('woocommerce_before_cart_totals', 'woocommerce_calculate_totals', 30);
add_action('woocommerce_after_calculate_totals', 'woocommerce_calculate_totals', 30);
感谢任何帮助。
答案 0 :(得分:0)
您没有在woocommerce_calculate_totals
函数中累积小计。您每次都在写$cart_sub_total = $final_price;
,所以最后只剩下最后一项的价格。相反,它应该是$cart_sub_total = $cart_sub_total + $final_price;
。