douguan1887 2014-12-30 19:11
浏览 14
已采纳

根据项目检查并添加到购物车

I would like to check the cart for ITEM A,

if ITEM A is present add ITEM B,

if BOTH are present DO NOTHING.

I have this code below to work with. Its working but need to check if both items are in cart and not add another item. Thanks for any help.

// 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?
    }
}
}
  • 写回答

1条回答 默认 最新

  • droi5225 2014-12-30 19:41
    关注

    Assuming your original code works, here is how I would do it. I have renamed a variable or two for ease of reading.

    $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 {
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在不同的执行界面调用同一个页面
  • ¥20 基于51单片机的数字频率计
  • ¥50 M3T长焦相机如何标定以及正射影像拼接问题
  • ¥15 keepalived的虚拟VIP地址 ping -s 发包测试,只能通过1472字节以下的数据包(相关搜索:静态路由)
  • ¥20 关于#stm32#的问题:STM32串口发送问题,偶校验(even),发送5A 41 FB 20.烧录程序后发现串口助手读到的是5A 41 7B A0
  • ¥15 C++map释放不掉
  • ¥15 Mabatis查询数据
  • ¥15 想知道lingo目标函数中求和公式上标是变量情况如何求解
  • ¥15 关于E22-400T22S的LORA模块的通信问题
  • ¥15 求用二阶有源低通滤波将3khz方波转为正弦波的电路