【问题标题】:woocommerce product dependency: variations that cannot be bought alonewoocommerce 产品依赖性:不能单独购买的变体
【发布时间】:2019-03-08 19:42:27
【问题描述】:

有没有办法设置特定的产品变体,以便在购物车中没有其他产品的情况下无法购买?

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

所以我正在寻找一种方法来防止只购买“70g”的变体,因为这些变体本身并没有盈利。

我发现此代码可以为购物车设置最低订单价值并显示通知,但我不知道如何针对变化调整此代码并禁用按钮:https://docs.woocommerce.com/document/minimum-order-amount/

【问题讨论】:

    标签: php woocommerce


    【解决方案1】:

    我通过为单个产品指定特定类别找到了解决方案。然后它会在购物车仅包含该类别之外的产品并拒绝结帐时显示通知:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-16
      相关资源
      最近更新 更多