php - 以编程方式从购物篮中删除产品
问题描述
当购物车总数超过一定数量时,我正在使用以下代码将免费产品添加到购物篮中。
当我低于购物车总数时,它会命中 if 语句,但不会删除产品。
我认为这可能是因为购物篮表单上的数量设置为 1,而我的代码没有覆盖该数量以将其设置为 0(并删除它)。
还有其他方法可以删除或覆盖它吗?
/*
* Automatically adding the product to the cart when cart total amount reach to £20.
*/
function aapc_add_product_to_cart() {
global $woocommerce;
$cart_total = 20;
$free_product_id = 85028; // Product Id of the free product which will get added to cart
if ( $woocommerce->cart->total >= $cart_total ) {
echo "Over the limit";
$quantity = 1;
WC()->cart->add_to_cart( $free_product_id, $quantity );
} elseif($woocommerce->cart->total < $cart_total) {
echo "Under the limit";
$quantity = 0;
WC()->cart->remove_cart_item( $free_product_id, $quantity );
}
}
add_action( 'template_redirect', 'aapc_add_product_to_cart' );
我试过使用这个问题,但无法让它工作,它甚至不会将项目添加到我的购物篮中。
如果有帮助,我正在使用 Woocommerce 3.6.5 版。
解决方案
/*
* Automatically adding the product to the cart when cart total amount reach to £20.
*/
function aapc_add_product_to_cart() {
global $woocommerce;
$cart_total = 20;
$free_product_id = 85028; // Product Id of the free product which will get added to cart
if ( WC()->cart->total >= $cart_total ) {
$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 );
}
} elseif(WC()->cart->total < $cart_total) {
$quantity = 0;
$prod_unique_id = WC()->cart->generate_cart_id( $free_product_id );
// Remove it from the cart by un-setting it
unset( WC()->cart->cart_contents[$prod_unique_id] );
WC()->cart->remove_cart_item( $free_product_id );
}
}
add_action( 'woocommerce_after_calculate_totals', 'aapc_add_product_to_cart' );
推荐阅读
- sonarqube - SONAR 代码覆盖率没有得到反映
- huawei-mobile-services - 我需要访问HUAWEI AppGallery Connect API并通过PMS API(服务器API)创建产品。但是 403 客户端令牌授权失败
- angular - Angular 11:步进器中形成多个字段
- python - 使用 xarray 将 netcdf 文件的一部分转换为数据框
- java - 使用 XMLBeans 4.0.0 版和 xmlbeans-maven-plugin 2.3.3 的模式类生成失败
- linux - 非持久性系统范围的环境变量
- python-3.x - 当前路径 chat/room/1/ 与其中任何一个都不匹配
- osgi - Karaf 从 4.2.0.M1 升级到 4.2.0.M2 出现错误
- jenkins - 詹金斯声纳扫描仪显示警告
- java - 为 Kafka Consumer 随机生成的组 ID