gpt4 book ai didi

php - 添加到购物车每个产品的最大数量并在 WooCommerce 中进行验证

转载 作者:行者123 更新时间:2023-12-03 08:35:51 25 4
gpt4 key购买 nike

我想限制“添加到购物车”按钮的每个产品的最大数量为 10 个。我希望客户每个订单购买的每种产品的数量不能超过 10 个。

这是代码

add_filter( 'woocommerce_add_to_cart_validation', 'restrict_per_product_quantity' );
function restrict_per_product_quantity($cart_item_data) {
global $woocommerce;
$item_count = $woocommerce->cart->cart_contents_count;
if($item_count > 10) {
wc_add_notice( 'Sorry, Only 10 quantity per product per order is allowed. If you would like to order more please contact support.', 'error' );
return false;
}
return $cart_item_data;
}

问题是此代码不适用于每个产品,它会检查购物车,如果购物车中有 10 件商品,则会显示错误。

最佳答案

  • woocommerce_add_to_cart_validation 包含 5 个您可以使用的参数
  • 通过代码中添加的注释进行解释
function filter_woocommerce_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = null, $variations = null ) {
// Set max allowed
$max_allowed = 10;

// Error message
$message = 'max ' . $max_allowed . ' products allowed';

// quantity > max allowed || elseif = when cart not empty
if ( $quantity > $max_allowed ) {
wc_add_notice( __( $message, 'woocommerce' ), 'error' );
$passed = false;
} elseif ( ! WC()->cart->is_empty() ) {
// Get current product id
$product_id = $variation_id > 0 ? $variation_id : $product_id;

// Cart id
$product_cart_id = WC()->cart->generate_cart_id( $product_id );

// Find product in cart
$in_cart = WC()->cart->find_product_in_cart( $product_cart_id );

// True
if ( $in_cart ) {
// Get cart
$cart = WC()->cart->get_cart();

// Current quantity in cart
$quantity_in_cart = $cart[$product_cart_id]['quantity'];

// Condition: quanitity in cart + new add quantity greater than max allowed
if ( $quantity_in_cart + $quantity > $max_allowed ) {
wc_add_notice( __( $message, 'woocommerce' ), 'error' );
$passed = false;
}
}
}

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

关于php - 添加到购物车每个产品的最大数量并在 WooCommerce 中进行验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63893595/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com