woocommerce产品依赖性:无法单独购买的变体

时间:2019-03-07 09:15:07

标签: php woocommerce

是否可以设置特定的产品变体,以便在没有其他产品的情况下不能购买?

示例: 我的商店里有10种产品,每种产品都有“ 70g”,“ 1kg”和“ 2kg”两种变体。现在,如果您的购物车中有“ 70g”变体,而没有另一个具有较高价值的变体,则应显示一个通知,并禁用结帐按钮。

所以我正在寻找一种方法来防止仅购买“ 70g”的变体,因为仅这些变体并不能带来利润。

我发现此代码可以使购物车的最低订单金额达到最低要求并显示通知,但我不知道如何针对变化和禁用按钮进行调整:https://docs.woocommerce.com/document/minimum-order-amount/

1 个答案:

答案 0 :(得分:0)

我通过为单个产品指定特定类别找到了解决方案。然后,当购物车中的产品仅属于该类别并且拒绝结帐时,它会显示一条通知:

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