首页 > 解决方案 > 在 Woocommerce 购物车中自动添加或删除免费产品,但在购物车中不包含订阅产品

问题描述

您好,这是与下面的链接类似的问题,但只是想问一下,如果购买的产品是订阅类型,是否可以设置不加载免费产品的条件?谢谢你。 在 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
 */

标签: phpwordpressfunctionwoocommerce

解决方案


    add_action( 'template_redirect', 'add_product_to_cart_conditionally' );
function add_product_to_cart_conditionally() {
    if ( is_admin() )  return; // Exit

    // 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 );
    }
}

推荐阅读