首页 > 解决方案 > 以编程方式从购物篮中删除产品

问题描述

当购物车总数超过一定数量时,我正在使用以下代码将免费产品添加到购物篮中。

当我低于购物车总数时,它会命中 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 版。

标签: phpwoocommerce

解决方案


/*
* 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' );

推荐阅读