Home > Enterprise >  add to cart button disappear if I use quntity feild
add to cart button disappear if I use quntity feild

Time:07-05

I'm trying to add "quantity field" for each product in shop page

add_filter( 'woocommerce_loop_add_to_cart_link', 'quantity_inputs_for_woocommerce_loop_add_to_cart_link', 10, 2 );
function quantity_inputs_for_woocommerce_loop_add_to_cart_link( $html, $product ) {
    if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {
        $html = '<form action="' . esc_url( $product->add_to_cart_url() ) . '"  method="post" enctype="multipart/form-data">';
        // Access the cart items
        foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
            $product_id = $cart_item['product_id'];
            $quantity = $cart_item['quantity'];
        }
        // If we have match update quantity
        if($product_id == $product->get_ID()) {
            $html .= woocommerce_quantity_input( array('input_value' => $quantity), $product, false );
        } else {
            $html .= woocommerce_quantity_input( array(), $product, false );
        }
        $html .= '<button type="submit" >' . esc_html( $product->add_to_cart_text() ) . '</button>';
        $html .= '</form>';
    }
    return $html;
}

It works, but the problem is; If I use the quantity field and pressed add to cart button, the button will disappear, and ONLY when deleting the cart the add to cart button will show up again.

What I'm doing wrong?

CodePudding user response:

You have to change the foreach loop

function quantity_inputs_for_woocommerce_loop_add_to_cart_link( $html, $product ) {
    if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {
        $html = '<form action="' . esc_url( $product->add_to_cart_url() ) . '"  method="post" enctype="multipart/form-data">';
        // Access the cart items
        $in_cart = false;
        foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
            $product_id = $cart_item['product_id'];
            $quantity = $cart_item['quantity'];
            if($product_id == $product->get_ID()){
                $in_cart = true;
                break;
            }
        }
        // If we have match update quantity
        if($in_cart) {
            $html .= woocommerce_quantity_input( array('input_value' => $quantity), $product, false );
        } else {
            $html .= woocommerce_quantity_input( array(), $product, false );
        }
        $html .= '<button type="submit" >' . esc_html( $product->add_to_cart_text() ) . '</button>';
        $html .= '</form>';
    }
    return $html;
}
  • Related