满足购物车总数时自动向Woocommerce购物车添加免费商品

时间:2019-05-22 18:47:43

标签: php woocommerce

下面我有一些代码,当购物车总额达到25美元时,购物车中会显示免费商品。这部分工作正常。当用户从购物车中取出一个商品,使购物车的总金额少于$ 25时,免费商品就会自行删除。我遇到的问题是用户无法从购物车中手动删除免费商品。我希望用户可以选择删除免费商品,同时保持购物车总额超过25美元。以下是我用来创建免费商品添加和删除的代码。

/*
 * Automatically adding the catalog to the cart when cart total amount reach to $25.
 */
function aapc_add_product_to_cart() {
    global $woocommerce;

    $cart_total = 25;   
    if ( $woocommerce->cart->total >= $cart_total ) {
        if ( ! is_admin() ) {
            $free_product_id = 101861;  // 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 );
            }        
        }
    }        
}
add_action( 'template_redirect', 'aapc_add_product_to_cart' );

add_action( 'template_redirect', 'remove_product_from_cart' );
function remove_product_from_cart() {
    // Run only in the Cart or Checkout Page
    global $woocommerce;
    $current =  WC()->cart->cart_contents_total;
    $min_amount= 25;
    $prod_to_remove = 101861;
    if ( $current < $min_amount) {
        if( is_cart() || is_checkout() ) {

            // Cycle through each product in the cart
            foreach( WC()->cart->cart_contents as $prod_in_cart ) {
                // Get the Variation or Product ID
                $prod_id = ( isset( $prod_in_cart['variation_id'] ) && 
                $prod_in_cart['variation_id'] != 0 ) ? $prod_in_cart['variation_id'] : $prod_in_cart['product_id'];
                // Check to see if IDs match
                if( $prod_to_remove == $prod_id ) {
                    // Get it's unique ID within the Cart
                    $prod_unique_id = WC()->cart->generate_cart_id( $prod_id );
                    // Remove it from the cart by un-setting it
                    unset( WC()->cart->cart_contents[$prod_unique_id] );
                }
            }
        }
    }
}

0 个答案:

没有答案