WooCommerce产品依赖性:无法单独购买的变化



是否有一种方法可以设置特定产品变化,以免在购物车中购买其他产品?

示例:我有一个商店,有10种产品,每种产品都有" 70克"," 1kg"one_answers" 2kg"的变化。现在,如果您在卡车中具有" 70G"变化,而没有其他具有较高值的变化,则应出现通知,并且应禁用结帐按钮。

所以我正在寻找一种防止购买" 70克"的方法,因为仅这些变化就无法获利。

我找到了此代码是为了使购物车的最低订单值并显示通知,但我不知道如何对此进行调整以进行变化和禁用按钮:https://docs.woocommerce.com/document/document/minimen--order-order-order-amount/

我通过给出特定类别来找到单一产品的解决方案。然后,它显示了一个仅在该类别中的推车产品时的通知,并否认结帐:

/** Renders a notice and prevents checkout if the cart only contains products in a specific category */
function sv_wc_prevent_checkout_for_category() {
    //  If the cart is empty, then let's hit the ejector seat
    if (WC()->cart->is_empty()) {
        return;
    }   
    // set the slug of the category for which we disallow checkout
    $category = '70g';
    // get the product category
    $product_cat = get_term_by( 'slug', $category, 'product_cat' );
    // sanity check to prevent fatals if the term doesn't exist
    if ( is_wp_error( $product_cat ) ) {
        return;
    }
    $category_name = '<a href="' . get_term_link( $category, 'product_cat' ) . '">' . $product_cat->name . '</a>';
    // check if this category is the only thing in the cart
    if ( sv_wc_is_category_alone_in_cart( $category ) ) {
        // render a notice to explain why checkout is blocked
        wc_add_notice( sprintf( 'Du hast ausschließlich 70g-Probierpakete in deinem Warenkorb. Aus wirtschaftlichen Gründen können wir diese nur in Kombination mit anderen Produkten anbieten. Bitte füge daher weitere Produkte zu deiner Bestellung hinzu.', $category_name ), 'error' );
    }
}
add_action( 'woocommerce_check_cart_items', 'sv_wc_prevent_checkout_for_category' );
/**Checks if a cart contains exclusively products in a given category*/
function sv_wc_is_category_alone_in_cart( $category ) {   
    // check each cart item for our category
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {    
        // if a product is not in our category, bail out since we know the category is not alone
        if ( ! has_term( $category, 'product_cat', $cart_item['data']->id ) ) {
            return false;
        }
    }   
    // if we're here, all items in the cart are in our category
    return true;
}

最新更新