问题只允许 WooCommerce 购物车中的一种产品

时间:2021-06-01 08:08:35

标签: wordpress woocommerce product cart hook-woocommerce

我们有一个预订系统,它应该只允许购物车中的一种产品(当客户添加下一个产品时,应从购物车中删除前一个产品)。

直到今天我们一直在使用以下代码:

~5s

但它停止工作(我找不到原因)。最近版本的 WooCommerce 有什么变化吗?我怎样才能让它再次工作?

1 个答案:

答案 0 :(得分:2)

您可以改用 WC()->cart->empty_cart();

function filter_woocommerce_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = null, $variations = null ) {
    // When NOT empty
    if ( ! WC()->cart->is_empty() ) {
        // Empties the cart and optionally the persistent cart too.
        WC()->cart->empty_cart();
    }

    return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'filter_woocommerce_add_to_cart_validation', 10, 5 );

如果上述方法由于某种原因不起作用,您也可以通过以下方式应用:(PHP 7.3 及更高版本的解决方案)

// Used to calculate totals
function action_woocommerce_before_calculate_totals( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;
    
    // Get cart
    $get_cart = $cart->get_cart();

    // Solution for PHP 7.3 and up
    foreach ( $get_cart as $cart_item_key => $cart_item ) {
        // NOT last element
        if ( $cart_item_key !== array_key_last( $get_cart ) ) {
            // Remove a cart item
            $cart->remove_cart_item( $cart_item_key );
        }
    }
}
add_action( 'woocommerce_before_calculate_totals', 'action_woocommerce_before_calculate_totals', 10, 1 );