我目前正在与WooCommerce建立一个网上商店,我推出了这款购物车,您可以随时在任何页面访问,您可以更新购物车内的产品数量。每当我这样做时,问题就会发生。例如,当我尝试获取WC()->cart->total
时,它返回0.
但是当我进入结帐页面时,它显示了所有正确的购物车数据,所以这让我觉得我错过了一些action
我必须在调整购物车中的东西后运行。我一直在查看set_quantity()
个功能,它会自动刷新$this->calculate_totals();
(手动尝试)。
Ajax功能:
public function set_quantity($direction = false, $product_id) {
$response = array();
$justOne = false;
if($_GET['data']['direction'] && $_GET['data']['product_id']) {
$direction = $_GET['data']['direction'];
$product_id = $_GET['data']['product_id'];
$justOne = true;
}
foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
$_product = $values['data'];
if ($product_id == $_product->id) {
if($justOne && $direction == 'minus') {
WC()->cart->set_quantity($cart_item_key, $values['quantity'] - 1, true);
$response['success']['quantity'] = $values['quantity'] - 1;
} else if($justOne && $direction == 'plus') {
WC()->cart->set_quantity($cart_item_key, $values['quantity'] + 1, true);
$response['success']['quantity'] = $values['quantity'] + 1;
} else {
WC()->cart->set_quantity($cart_item_key, $values['quantity'] + $direction, true);
}
$response['success']['line_total'] = '€ '.number_format((float)$response['success']['quantity'] * $_product->price, 2, '.', '');
$response['success']['cart_count'] = WC()->cart->get_cart_contents_count();
$response['success']['total'] = number_format((float)WC()->cart->total, 2, '.', '');
die(json_encode($response));
}
}
return false;
}
答案 0 :(得分:1)
使用此修改后的ajax函数。我对此进行了测试。它会起作用。
修改了Ajax功能:
public function set_quantity($direction = false, $product_id) {
$response = array();
$justOne = false;
if($_GET['data']['direction'] && $_GET['data']['product_id']) {
$direction = $_GET['data']['direction'];
$product_id = $_GET['data']['product_id'];
$justOne = true;
}
foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
$_product = $values['data'];
if ($product_id == $_product->id) {
if($justOne && $direction == 'minus') {
WC()->cart->set_quantity($cart_item_key, $values['quantity'] - 1, true);
$response['success']['quantity'] = $values['quantity'] - 1;
} else if($justOne && $direction == 'plus') {
WC()->cart->set_quantity($cart_item_key, $values['quantity'] + 1, true);
$response['success']['quantity'] = $values['quantity'] + 1;
} else {
WC()->cart->set_quantity($cart_item_key, $values['quantity'] + $direction, true);
}
if ( ! defined( 'WOOCOMMERCE_CART' ) ) {
define( 'WOOCOMMERCE_CART', true );
}
WC()->cart->calculate_totals();
$response['success']['line_total'] = '€ '.number_format((float)$response['success']['quantity'] * $_product->price, 2, '.', '');
$response['success']['cart_count'] = WC()->cart->get_cart_contents_count();
$response['success']['total'] = number_format((float)WC()->cart->total, 2, '.', '');
die(json_encode($response));
}
}
return false;
}