0

当用户访问数量为 0 的购物车页面时,我需要我的购物车页面自动添加产品,我尝试通过以下方式更改它:

我尝试了代码 1 和代码 2 的一些变化,但是当我点击更新购物车时,数量又变为零。对于该产品,尽管总数保持不变。应该是当我更新购物车时不应删除数量为零的购物车项目,并且我从 0 更改为 1 的该产品的数量应该达到 1。

代码 1

function add_product_to_cart_new() {
    if ( ! is_admin() ) {
        $product_id = array(2595,2594,1404,2650,1410,2652); //replace with your own product id
        $found = false;
        //check if product already in cart
        if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
            foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
                $_product = $values['data'];
                
                if (in_array($_product->get_id(), $product_id))
                //if ( $_product->get_id() == $product_id )
                    $found = true;
            }
             //if product not found, add it
            if ( ! $found )
              
                    foreach($product_id as $ids ){
                    WC()->cart->add_to_cart( $ids);
                    }
        } else {
             //if no products in cart, add it
                    foreach($product_id as $ids ){
                    WC()->cart->add_to_cart( $ids);
                    }
        }
    }
}

然后在代码下方 (input_value) 使其在购物车页面上为零。

代码 2

add_filter( 'woocommerce_quantity_input_args', 'jk_woocommerce_quantity_input_args', 10, 2 ); // Simple products

function jk_woocommerce_quantity_input_args( $args, $product ) {
    
    //if ( is_singular( 'product' ) ) {
     if(  is_cart() ){
        $args['input_value']    = 0;    // Starting value (we only want to affect  cart page)
     }
    //}
    $args['max_value']  = 80;   // Maximum value
    $args['min_value']  = 0;    // Minimum value
    $args['step']       = 1;    // Quantity steps
    return $args;
}

预期结果如下: http: //www.ecotechlube.com/cart/

4

1 回答 1

0

这并不完美,但这是我发现的唯一方法。

首先,您需要将产品添加到购物车中,数量很少,如下所示:

WC()->cart->add_to_cart($product_id, 0.00000001);

然后您需要在购物车和结帐模板中进行检查,如下所示:

if($cart_item['quantity'] == 0.00000001) $cart_item['quantity'] = 0;
于 2020-04-13T10:42:08.260 回答