【发布时间】:2021-04-08 22:58:05
【问题描述】:
如果订单总额高于 199.99 美元,我正在尝试将免费产品添加到购物车
我已经实现了这一点,它正在发挥作用。问题是,如果用户随后从购物车中删除了一个商品并再次低于 199.99 美元(以防止游戏系统),我需要删除该产品。
我所拥有的似乎正在工作。问题是我似乎需要在 REMOVE FROM CART 操作似乎起作用(或刷新页面)之前单击 2 个链接。
这是什么原因造成的?是否可以通过 AJAX 完成删除操作?
// -------------------------------------------
// ADD PRODUCT IF ORDER MINIMUM ABOVE 200
/*
* Automatically adding the product to the cart when cart total amount reach to $199.99.
*/
function aapc_add_product_to_cart() {
global $woocommerce;
$cart_total = 199.99;
if ( $woocommerce->cart->total >= $cart_total ) {
if ( is_user_logged_in() ) {
$free_product_id = 339; // Product Id of the free product which will get added to cart
$found = false;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->get_id() == $free_product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $free_product_id );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $free_product_id );
}
}
}
if ( $woocommerce->cart->total <= $cart_total && $found ) {
WC()->cart->remove_cart_item( $free_product_id );
}
}
add_action( 'template_redirect', 'aapc_add_product_to_cart' );
add_action( 'template_redirect', 'remove_product_from_cart_programmatically' );
function remove_product_from_cart_programmatically() {
if ( is_admin() ) return;
$product_id = 339; // product id
$cart_total = 199.99;
$in_cart = false;
foreach( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( $cart_item['product_id'] === $product_id ) {
$in_cart = true;
$key = $cart_item_key;
break;
}
}
if( WC()->cart->total < $cart_total ) {
if ( $in_cart ) WC()->cart->remove_cart_item( $key );
}
}
【问题讨论】:
-
请同时包含您的 html 和 javascript 代码
-
HTML 是标准的 wordpress/woocommerce 内容。这是通过 Functions.php 执行的,没有使用 javascript。纯 PHP。
-
那么恐怕你需要使用 Ajax 进行动态更新
-
@RonnieMcDonte 您只需要使用与购物车相关的挂钩,该挂钩由 AJAX 驱动,如下面的答案所示,对您的代码进行一些更改。
标签: php wordpress woocommerce product cart