电子商务。如果产品不在购物车中,请从购物车中删除其他产品。不工作

时间:2021-05-17 10:08:24

标签: php wordpress woocommerce hook-woocommerce

我想在 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();
}}

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

1 个答案:

答案 0 :(得分:2)

我修改了你的代码。

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();
    }
}
相关问题