我有一个功能,可以将购物车中的最大商品数量设置为16。因此,用户不能结帐超过16件商品。
我还正在运行一个插件,该插件在添加优惠券时会向free_gift
添加一个$cart_item array
密钥。
问题在于,当用户添加16项+ free_gift
=总数为17项时,无法进行结帐。
如何将free_gift
从添加到购物车中的数量中删除?
示例:
free_gift
= 16个项目free_gift
= 12项到目前为止,我的代码允许添加free_gifts超过最大16个限制,但不应用16个项目的最大规则:
// Set a maximum number of products requirement before checking out
add_action( 'woocommerce_check_cart_items', 'spyr_set_max_num_products' );
function spyr_set_max_num_products() {
// Only run in the Cart or Checkout pages
if( is_cart() || is_checkout() ) {
$cart_num_products = 0;
foreach ( WC()->cart->cart_contents as $cart_item_key => $cart_item ) {
// HERE I AM TRYING TO SKIP AND PREVENT CART ITEMS OF FREE_GIFTS BEING COUNTED
if ( isset( $cart_item['free_gift'] ) ) {
continue;
}
// Count for regular products.
$cart_num_products++;
}
// Set the maximum number of products before checking out
$maximum_num_products = 16;
// Compare values and add an error is Cart's total number of products
// happens to be less than the minimum required before checking out.
// Will display a message along the lines of
// A Maximum of 16 products is allowed before checking out. (Cont. below)
if( $cart_num_products > $maximum_num_products ) {
// Display our error message
wc_add_notice( sprintf( '<strong>A Maximum of %s snacks are allowed per order.</strong>'
. '<br />Current number of snacks: %s.',
$maximum_num_products,
$cart_num_products ),
'error' );
}
}
}
答案 0 :(得分:1)
尝试以下操作,这将从购物车中删除您的自定义免费商品:
add_action( 'woocommerce_check_cart_items', 'max_allowed_cart_items' );
function max_allowed_cart_items() {
// Only run in the Cart or Checkout pages
if( is_cart() || is_checkout() ) {
// Set the maximum number of products before checking out
$max_items_count = 16;
$cart_items_count = WC()->cart->get_cart_contents_count( );
foreach ( WC()->cart->get_cart() as $cart_item ) {
if ( isset( $cart_item['free_gift'] ) ) {
$cart_items_count -= $cart_item['quantity'];
}
}
if( $cart_items_count > $max_items_count ) {
// Display our error message
wc_add_notice( sprintf( '<strong>A Maximum of %s snacks are allowed per order.</strong>'
. '<br />Current number of snacks: %s.',
$max_items_count,
$cart_items_count ),
'error' );
}
}
}
代码进入您的活动子主题(或活动主题)的function.php文件中。应该可以。
答案 1 :(得分:0)
首先检查免费物品是否在购物车中。在这种情况下,您需要先计算函数中的“ -1”项,然后才能使用结帐功能。
function free_product_in_cart($free_product_id) {
$free_product_cart_id = WC()->cart->generate_cart_id( $free_product_id );
return WC()->cart->find_product_in_cart( $free_product_cart_id ); //Return true when the free product is in the cart
}
因此,您随后更新逻辑以进行检查:
if(free_product_in_cart(your product id) {
$free_item_space = 1;
} else {
$free_item_space = 0;
}
if( $cart_num_products > $maximum_num_products + $free_item_space) {
// Display our error message
wc_add_notice( sprintf( '<strong>A Maximum of %s snacks are allowed per order.</strong>'
. '<br />Current number of snacks: %s.',
$maximum_num_products,
$cart_num_products ),
'error' );
}