簡體   English   中英

自動添加或刪除 Woocommerce 購物車中的免費產品,但購物車上沒有訂閱產品

[英]Add or remove automatically a free product in Woocommerce cart but not with subscription product on the cart

您好,這是與下面的鏈接類似的問題,但只是想問一下,如果購買的產品是訂閱類型,是否可以設置不加載免費產品的條件? 謝謝你。 在 Woocommerce 購物車中自動添加或刪除免費產品

/**
 * Add another product depending on the cart total
 */

add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
  if ( ! is_admin() ) {
        global $woocommerce;
        $product_id = 85942; //replace with your product id
        $found = false;
        $cart_total = 15; //replace with your cart total needed to add above item

        if( $woocommerce->cart->total >= $cart_total ) {
            //check if product already in cart
            if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {

                $isVirtualOnly = false;
                foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values) {
                    $_product = $values[‘data’];
                    if ($_product != null)
                        if ($_product->get_type() != $_virtual)
                                $isVirtualOnly = false;
                }

                if ($isVirtualOnly != true) {
                    foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
                        $_product = $values['data'];
                        if ( $_product->get_id() == $product_id )
                            $found = true;
                    }
                    // if product not found, add it
                    if ( ! $found )
                        $woocommerce->cart->add_to_cart( $product_id );
                }
            } else {
                    // if no products in cart, add it
                    $woocommerce->cart->add_to_cart( $product_id );
            }
        }
    }
}

/**
 * END Add another product depending on the cart total
 */
add_action( 'template_redirect', 'add_product_to_cart_conditionally' );

function add_product_to_cart_conditionally() { if ( is_admin() ) return; // 出口

// Below define the product Id to be added:
$product_A = 37; // <== For new customers that have not purchased a product before (and guests)
$product_B = 53; // <== For confirmed customers that have purchased a product before

$product_id = has_bought() ? $product_B : $product_A;

// If cart is empty
if( WC()->cart->is_empty() ) {
    WC()->cart->add_to_cart( $product_id ); // Add the product
}
// If cart is not empty
else {
    // Loop through cart items (check cart items)
    foreach ( WC()->cart->get_cart() as $item ) {
        // Check if the product is already in cart
        if ( $item['product_id'] == $product_id ) {
            return; // Exit if the product is in cart
        }
    }
    // The product is not in cart: We add it
    WC()->cart->add_to_cart( $product_id );
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM