LVD*_*VDM 9 php ajax wordpress jquery woocommerce
我目前正在与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;
}
Run Code Online (Sandbox Code Playgroud)
使用这个修改过的ajax函数。我已经测试过这个。它会起作用的。
\n\n修改Ajax功能:
\n\npublic function set_quantity($direction = false, $product_id) {\n $response = array();\n $justOne = false;\n\n if($_GET['data']['direction'] && $_GET['data']['product_id']) {\n $direction = $_GET['data']['direction'];\n $product_id = $_GET['data']['product_id'];\n $justOne = true;\n }\n\n foreach (WC()->cart->get_cart() as $cart_item_key => $values) {\n $_product = $values['data'];\n if ($product_id == $_product->id) {\n\n if($justOne && $direction == 'minus') {\n WC()->cart->set_quantity($cart_item_key, $values['quantity'] - 1, true);\n $response['success']['quantity'] = $values['quantity'] - 1;\n } else if($justOne && $direction == 'plus') {\n WC()->cart->set_quantity($cart_item_key, $values['quantity'] + 1, true);\n $response['success']['quantity'] = $values['quantity'] + 1;\n } else {\n WC()->cart->set_quantity($cart_item_key, $values['quantity'] + $direction, true);\n }\n\n if ( ! defined( 'WOOCOMMERCE_CART' ) ) {\n define( 'WOOCOMMERCE_CART', true );\n }\n WC()->cart->calculate_totals();\n\n $response['success']['line_total'] = '\xe2\x82\xac '.number_format((float)$response['success']['quantity'] * $_product->price, 2, '.', '');\n $response['success']['cart_count'] = WC()->cart->get_cart_contents_count();\n $response['success']['total'] = number_format((float)WC()->cart->total, 2, '.', '');\n die(json_encode($response));\n }\n }\n return false;\n}\n
Run Code Online (Sandbox Code Playgroud)\n