10

我正在使用 Woocommerce 并需要以下内容:

  1. 由于产品正在销售到另一个国家,而那个国家的海关只允许总共 6 个,所以我需要防止客户订购超过 6 个项目(产品)。

  2. 6 是项目或产品的总数。客户可以订购 1 件产品,数量为 6 或 2 件产品,每件数量为 3。海关只允许物品总数为 6 件。

  3. 如果购物车中有超过 6 件商品,则会出现警告并阻止客户继续结帐。

这是否可以将购物车项目限制为 6 个并在超出此限制时显示一条消息?

4

2 回答 2

29

如果要限制购物车物品,有 2 个操作可以检查和控制:

  • 将产品添加到购物车时(在商店页面和产品页面中)
  • 当购物车页面中的数量更新时

使用挂在woocommerce_add_to_cart_validation过滤器挂钩中的自定义函数,将允许您将购物车项目限制为最多 6 个,并在超出此限制时显示自定义消息:

// Checking and validating when products are added to cart
add_filter( 'woocommerce_add_to_cart_validation', 'only_six_items_allowed_add_to_cart', 10, 3 );

function only_six_items_allowed_add_to_cart( $passed, $product_id, $quantity ) {

    $cart_items_count = WC()->cart->get_cart_contents_count();
    $total_count = $cart_items_count + $quantity;

    if( $cart_items_count >= 6 || $total_count > 6 ){
        // Set to false
        $passed = false;
        // Display a message
         wc_add_notice( __( "You can’t have more than 6 items in cart", "woocommerce" ), "error" );
    }
    return $passed;
}

使用挂在woocommerce_update_cart_validation过滤器钩子中的自定义函数,将允许您控制购物车项目数量更新到您的 6 个购物车项目限制,并在超过此限制时显示自定义消息:

// Checking and validating when updating cart item quantities when products are added to cart
add_filter( 'woocommerce_update_cart_validation', 'only_six_items_allowed_cart_update', 10, 4 );
function only_six_items_allowed_cart_update( $passed, $cart_item_key, $values, $updated_quantity ) {

    $cart_items_count = WC()->cart->get_cart_contents_count();
    $original_quantity = $values['quantity'];
    $total_count = $cart_items_count - $original_quantity + $updated_quantity;

    if( $cart_items_count > 6 || $total_count > 6 ){
        // Set to false
        $passed = false;
        // Display a message
         wc_add_notice( __( "You can’t have more than 6 items in cart", "woocommerce" ), "error" );
    }
    return $passed;
}

代码在您的活动子主题(或主题)的 function.php 文件中或任何插件文件中。

此代码经过测试并且有效

于 2017-09-01T22:08:31.357 回答
7

在验证添加到购物车的产品时,您可以添加其他验证参数。根据产品是否可以添加到购物车,woocommerce_add_to_cart_validation期望返回一个true或值:false

/**
 * When an item is added to the cart, check total cart quantity
 */
function so_21363268_limit_cart_quantity( $valid, $product_id, $quantity ) {

    $max_allowed = 6;
    $current_cart_count = WC()->cart->get_cart_contents_count();

    if( ( $current_cart_count > $max_allowed || $current_cart_count + $quantity > $max_allowed ) && $valid ){
        wc_add_notice( sprint( __( 'Whoa hold up. You can only have %d items in your cart', 'your-plugin-textdomain' ), $max ), 'error' );
        $valid = false;
    }

    return $valid;

}
add_filter( 'woocommerce_add_to_cart_validation', 'so_21363268_limit_cart_quantity', 10, 3 );
于 2017-09-01T20:36:08.073 回答