【问题标题】:WooCommerce cart validation: check that specific product is always added before other productsWooCommerce 购物车验证:检查是否始终在其他产品之前添加特定产品
【发布时间】:2020-07-05 18:00:43
【问题描述】:

说明:

我有一个用例,我需要在客户将其他产品添加到购物车之前检查特定产品是否已添加到购物车。

背景:

我们根据包裹(即产品)出租产品。套餐包括多个产品,产品没有价格,套餐有。所以基本上你需要将一个包(有价格)和产品(没有价格)添加到购物车。

问题:

目前客户可以在包裹前添加产品,他们可以继续在购物车中购物。

我所取得的一些进展:

if ( ! WC()->cart->is_empty() )
    foreach( WC()->cart->get_cart() as $cart_item )
    // now i would need to check if cart consists a package

我可以像这样解决在购物车中没有包裹的情况下将产品添加到购物车的问题:

if (WC()->cart->is_empty() )
//then don't add product to cart, tell customer to add package first.

【问题讨论】:

    标签: php wordpress validation woocommerce cart


    【解决方案1】:
    • 使用woocommerce_add_to_cart_validation 钩子
    • 注释并在代码中添加解释
    function filter_woocommerce_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = null, $variations = null ) {
        // Product (ID) in cart
        $product_first_in_cart = 30;
        
        // Compare
        if ( $product_first_in_cart != $product_id ) {
            // Set variable
            $in_cart = false;
            
            // Cart NOT empty
            if ( ! WC()->cart->is_empty() ) {
                // Loop trough cart
                foreach( WC()->cart->get_cart() as $cart_item ) {
                    // Search for the specific product
                    if ( $cart_item['data']->get_id() == $product_first_in_cart ) {
                        // Found, break loop
                        $in_cart = true;
                        break;
                    }
                }
            }
            
            // NOT in cart
            if ( ! $in_cart ) {
                wc_add_notice( __( 'Please add product "A" before adding other products', 'woocommerce' ), 'error' );
                $passed = false;
            }
        }
    
        return $passed;
    }
    add_filter( 'woocommerce_add_to_cart_validation', 'filter_woocommerce_add_to_cart_validation', 10, 5 );
    

    【讨论】:

    • 如果我想在 $product_first_in_cart = 30 中添加多个产品 ID,那么我需要修改 if ( $cart_item['data']->get_id() == $product_first_in_cart ) 部分吗?
    • 例如,如果 $product_first_in_cart = array(30,45,45);
    • 为此您可以使用in_array。调整代码取决于,例如,这些产品中的 1 个必须存在于购物车中,还是所有产品都必须存在于购物车中,然后才能添加其他产品。如果您无法弄清楚,请随时提出一个与此相关的新问题。但是,不要忘记将您所做的尝试添加到新问题中,以显示必要的承诺。问候
    猜你喜欢
    • 2020-04-28
    • 2015-09-12
    • 1970-01-01
    • 2014-11-21
    • 2018-11-13
    • 2014-02-06
    • 2015-10-17
    • 2014-09-14
    • 2018-10-13
    相关资源
    最近更新 更多