我想检查购物车中的项目 A,
如果存在项目 A,则添加项目 B,
如果两者都存在,则不执行任何操作。
我在下面有这个代码可以使用。它有效,但需要检查两个项目是否都在购物车中,而不是添加另一个项目。感谢您的任何帮助。
// add item to cart on visit
add_action( 'init', 'add_product_to_cart' );
function add_product_to_cart() {
if ( ! is_admin() ) {
global $woocommerce;
$product1_id = 66;
$product2_id = 88;
$found = false;
//check if product1 is in cart
if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->id == $product1_id )
$found = true;
}
// if product1 found, add product2
if ( $found )
$woocommerce->cart->add_to_cart( $product2_id );
} else {
// check for product2 here?
}
}
}
假设您的原始代码有效,以下是我将如何操作。为了便于阅读,我重命名了一两个变量。
$product_1_in_cart = false;
$product_2_in_cart = false;
if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->id == $product1_id )
$product_1_in_cart = true;
if ( $_product->id == $product2_id )
$product_2_in_cart = true;
}
// if product 1 is in cart, and product 2 is not in cart
if ( $product_1_in_cart && !$product_2_in_cart ){
$woocommerce->cart->add_to_cart( $product2_id );
}
} else {
}