【问题标题】:Woocommerce. if product is not in cart, remove additional product from cart. not working电子商务。如果产品不在购物车中,请从购物车中删除其他产品。不工作
【发布时间】:2021-05-17 10:08:24
【问题描述】:

我想在 woocommerce 中做这样的事情。如果特定产品 ID 只是购物车中的物品,我希望将购物车清空,这是我的代码:

add_action( 'woocommerce_before_calculate_totals', 'conditionally_remove_a_discounted_product' );
function conditionally_remove_a_discounted_product( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
    return;

// Settings
$discounted_product_id = array('2877','2876','2874','2873','2871','2833','2831','2832','2525','2524');

// Initializing variables
$discounted_item_key = false;

// Loop through cart items (first loop)
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ){
    // When free productis is cart
    if ( in_array( $discounted_product_id, array($cart_item['product_id'], $cart_item['variation_id']) ) ) {
        $discounted_item_key = $cart_item_key;
    }
    // if any other product is in cart: EXIT
    else {
       return;
    }  
}
// When the discounted product is alone in cart, remove it
if( $discounted_item_key ) {
    // display notice on removal (optional)
    wc_clear_notices();
    wc_add_notice( __("Cart Emptied"), 'notice' );

    WC()->cart->empty_cart();
}}

但它不起作用我能知道为什么吗?如果只有数组中的产品只是购物车中的物品,它不会清空购物车。

【问题讨论】:

    标签: php wordpress woocommerce hook-woocommerce


    【解决方案1】:

    我修改了你的代码。

    add_action( 'woocommerce_before_calculate_totals', 'conditionally_remove_a_discounted_product' );
    function conditionally_remove_a_discounted_product( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        // Settings
        $discounted_product_id = array('2877','2876','2874','2873','2871','2833','2831','2832','2525','2524');
    
        // Initializing variables
        $discounted_item_key = false;
    
        // Loop through cart items (first loop)
        foreach ( $cart->get_cart() as $cart_item_key => $cart_item ){
            // When free productis is cart
            if ( in_array( $cart_item['product_id'], $discounted_product_id ) || in_array( $cart_item['variation_id'], $discounted_product_id ) ) {
                $discounted_item_key = $cart_item_key;
            }
            // if any other product is in cart: EXIT
            else {
               return;
            }  
        }
        // When the discounted product is alone in cart, remove it
        if( $discounted_item_key ) {
            // display notice on removal (optional)
            wc_clear_notices();
            wc_add_notice( __("Cart Emptied"), 'notice' );
    
            WC()->cart->empty_cart();
        }
    }
    

    【讨论】:

    • 欢迎...很高兴为您提供帮助。
    猜你喜欢
    • 1970-01-01
    • 2022-06-16
    • 2020-02-17
    • 2022-08-23
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    • 2020-11-15
    • 1970-01-01
    相关资源
    最近更新 更多