I need to set up a custom add to cart button with the product ID added.
This is the code I have and it works perfectly.
function custom_add_to_cart_button_with_quantity_shortcode($atts) {
$product_id = isset($atts['product_id']) ? intval($atts['product_id']) : null;
if ($product_id) {
ob_start();
?>
<form action="<?php echo esc_url(wc_get_cart_url()); ?>" method="post" class="cart">
<div class="quantity">
<input type="button" value="-" class="minus">
<input type="number" step="1" min="1" max="" name="quantity" value="1" title="Qty" class="input-text qty text" size="4" pattern="[0-9]*" inputmode="numeric">
<input type="button" value="+" class="plus">
</div>
<button type="submit" class="single_add_to_cart_button button alt">Buy Now</button>
<input type="hidden" name="add-to-cart" value="<?php echo esc_attr($product_id); ?>">
</form>
<script>
jQuery(document).ready(function($) {
$(".plus").click(function() {
var currentVal = parseInt($('input[name="quantity"]').val());
if (!isNaN(currentVal)) {
$('input[name="quantity"]').val(currentVal + 1);
}
});
$(".minus").click(function() {
var currentVal = parseInt($('input[name="quantity"]').val());
if (!isNaN(currentVal) && currentVal > 1) {
$('input[name="quantity"]').val(currentVal - 1);
}
});
});
</script>
<?php
return ob_get_clean();
} else {
return 'ID del prodotto non valido.';
}
}
add_shortcode('custom_add_to_cart_button', 'custom_add_to_cart_button_with_quantity_shortcode');
The problem comes when I add two buttons, for two products, on the same page.
The quantity increment goes by two (1 – 3 – 5)
How can I solve this problem?`
New contributor
Imago is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.