购物车相同商品php,php – 限制购物车商品来自同一产品类别

这篇博客讨论了如何修改WooCommerce代码,确保购物车中只能包含特定产品类别的商品。作者最初使用has_term()函数检查'cat_x'类别商品,但现在希望阻止顾客将不同类别的商品加入购物车。当前代码能检测到'cat_x'商品并移除其他类别商品,但作者寻求进一步改进,使得购物车始终只包含同一类别的商品。
摘要由CSDN通过智能技术生成

当我在购物车中添加了特殊产品类别“cat_x”的商品并显示一些不同的自定义通知时,我使用下面的代码从购物车中删除其他WooCommerce产品类别商品.代码来自

this thread,效果很好:

add_action( 'woocommerce_check_cart_items', 'checking_cart_items' );

function checking_cart_items() {

$special = false;

$catx = 'cat_x';

$number_of_items = sizeof( WC()->cart->get_cart() );

if ( $number_of_items > 0 ) {

// Loop through all cart products

foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {

$item = $values['data'];

$item_id = $item->id;

// detecting if 'cat_x' item is in cart

if ( has_term( $catx, 'product_cat', $item_id ) ) {

if (!$special)

$special = true;

}

}

// Re-loop through all cart products

foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {

$item = $values['data'];

$item_id = $item->id;

if ( $special ) // there is a 'cat_x' item in cart

{

if ( $number_of_items == 1 ) { // only one 'cat_x' item in cart

if ( empty( $notice ) )

$notice = '1';

}

if ( $number_of_items >= 2 ) { // 'cat_x' item + other categories items in cart

// removing other categories items from cart

if ( !has_term( $catx, 'product_cat', $item_id ) ) {

WC()->cart->remove_cart_item( $cart_item_key ); // removing item from cart

if ( empty( $notice ) || $notice == '1' )

$notice = '2';

}

}

} else { // Only other categories items

if ( empty( $notice ) )

$notice = '3';

}

}

// Firing notices

if ( $notice == '1' ) { // message for an 'cat_x' item only (alone)

wc_add_notice( sprintf( '

bla bla bla one category X item in the cart

' ), 'success' );

} elseif ( $notice == '2' ) { // message for an 'cat_x' item and other ones => removed other ones

wc_add_notice( sprintf( '

bla bla bla ther is already category X in the cart => Other category items has been removed

' ), 'error' );

} elseif ( $notice == '3' ) { // message for other categories items (if needed)

wc_add_notice( sprintf( '

bla bla bla NOT category X in the cart

' ), 'success' );

}

}

}

条件函数has_term()是否也适用于类别数组,我尝试过而不是使用一个类别来设置该代码中的类别数组.但它不起作用.

但是,我的需求已经改变:我不想让顾客有可能选择不同类别的购物车商品.因此购物车必须始终包含来自同一产品类别的商品.

有什么帮助吗?

谢谢.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值