我从这个website中找到了这个很棒的片段
以下是检查购物车中是否存在特定产品的功能:
function woo_in_cart($product_id) {
global $woocommerce;
foreach($woocommerce->cart->get_cart() as $key => $val ) {
$_product = $val['data'];
if($product_id == $_product->id ) {
return true;
}
}
return false;
}
这可以在任何需要的地方使用:
if(woo_in_cart(123)) {
// Product is already in cart
}
问题是如何使用它来检查这样的多个产品:
if(woo_in_cart(123,124,125,126...)) {
// Product is already in cart
}
谢谢.
解决方法:
global $woocommerce
and$woocommerce->cart
is outdated and simply replaced byWC()->cart
这是一个自定义函数,其参数接受唯一的整数产品ID或产品ID数组,并返回购物车中匹配的ID数.
代码处理任何产品类型,包括可变产品和产品变体:
function matched_cart_items( $search_products ) {
$count = 0; // Initializing
if ( ! WC()->cart->is_empty() ) {
// Loop though cart items
foreach(WC()->cart->get_cart() as $cart_item ) {
// Handling also variable products and their products variations
$cart_item_ids = array($cart_item['product_id'], $cart_item['variation_id']);
// Handle a simple product Id (int or string) or an array of product Ids
if( ( is_array($search_products) && array_intersect($search_products, cart_item_ids) )
|| ( !is_array($search_products) && in_array($search_products, $cart_item_ids)
$count++; // incrementing items count
}
}
return $count; // returning matched items count
}
此代码位于活动子主题(活动主题或任何插件文件)的function.php文件中.
代码经过测试和运行.
用法:
1)对于唯一的产品ID(整数):
$product_id = 102;
// Usage as a condition in an if statement
if( 0 < matched_cart_items($product_id) ){
echo '<p>There is "'. matched_cart_items($product_id) .'"matched items in cart</p><br>';
} else {
echo '<p>NO matched items in cart</p><br>';
}
2)对于一系列产品ID:
$product_ids = array(102,107,118);
// Usage as a condition in an if statement
if( 0 < matched_cart_items($product_ids) ){
echo '<p>There is "'. matched_cart_items($product_ids) .'"matched items in cart</p><br>';
} else {
echo '<p>NO matched items in cart</p><br>';
}
3)对于3个或更多匹配购物车商品的产品ID数组,例如:
$product_ids = array(102, 107, 118, 124, 137);
// Usage as a condition in an if statement (for 3 matched items or more)
if( 3 <= matched_cart_items($product_ids) ){
echo '<p>There is "'. matched_cart_items($product_ids) .'"matched items in cart</p><br>';
} else {
echo '<p>NO matched items in cart</p><br>';
}