Product Quantity Input Shortcode

How to Create a Custom Product Quantity Input Shortcode with Plus and Minus Buttons in WordPress 2023: A User-Friendly Solution

Introduction

This WordPress code defines a custom Product Quantity Input shortcode that can be used to display a quantity input field with plus and minus buttons, allowing users to adjust the amount of a product before they put it in the shopping cart.

The shortcode can be used within WordPress pages or posts to add this functionality to a specific product.

Product Quantity Input Shortcode Function Setup


function add_to_cart_quantity_shortcode($atts) {
    global $product;
    $product_id = $product->id;
    $atts = shortcode_atts(array(
        'product_id' => $product_id,
    ), $atts, 'add_to_cart_quantity');

    // Rest of the code...
}
add_shortcode('add_to_cart_quantity', 'add_to_cart_quantity_shortcode');

The code defines a Product Quantity Input shortcode function named “add_to_cart_quantity_shortcode”. This function will handle the logic for generating a shortcode that adds a quantity input field with plus and minus buttons to the shopping cart.

The function takes an “$atts” (attributes) parameter, which represents the attributes passed to the shortcode when it is used in a post, page, or widget.

Inside the function, it accesses the global “$product” variable, which is presumed to contain information about the current product being displayed on the page. It retrieves the current product’s ID and stores it in the variable “$product_id”.

Then, using the `shortcode_atts` function, it merges the user-defined attributes with default values. In this case, the only attribute is “product_id”, and if it is not provided in the shortcode, the function will default to the ID of the current product.

Attribute Validation

if ($atts['product_id'] == 0) {
    return 'Invalid product ID.';
}

After obtaining the “product_id”` attribute from the “$atts” array, the code checks whether the value is equal to 0. If it is, it means that either the attribute is missing or invalid.

In such cases, the function returns the string “Invalid product ID.” This serves as a basic error-handling mechanism to inform the user that they need to provide a valid product ID to use the Product Quantity Input shortcode correctly.

Retrieve Quantity from Cart

$product_quantity = 0;
foreach (WC()->cart->get_cart() as $cart_item) {
    if ($cart_item['product_id'] == $atts['product_id']) {
        $product_quantity = $cart_item['quantity'];
        break;
    }
}

This section of the code is responsible for retrieving the current quantity of the specified product in the shopping cart.

It initializes the variable “$product_quantity” to 0, representing the default quantity when the product is not in the cart.

It then iterates through the items in the shopping cart using a foreach loop. For each cart item, it checks if the product ID matches the specified “product_id” attribute from the shortcode.

If a match is found, it means the product is already in the cart. The function updates “$product_quantity” with the quantity of the matching cart item and breaks out of the loop to avoid unnecessary iterations.

HTML Markup and JavaScript

ob_start();
?>
<div class="add-to-cart-quantity">
    <button class="minus-button">-</button>
    <input type="number" class="quantity" step="1" min="0" max="" name="quantity" value="<?php echo $product_quantity; ?>" title="Qty" size="4" pattern="[0-9]*" inputmode="numeric" title="text">
    <button class="plus-button">+</button>
</div>
<script>
    jQuery(document).ready(function($) {
        $('.add-to-cart-quantity').on('click', '.plus-button, .minus-button', function() {
            var $quantityInput = $(this).siblings('.quantity');
            var currentValue = parseInt($quantityInput.val());
            var step = $quantityInput.attr('step');
            step = parseInt(step);
            if ($(this).hasClass('plus-button')) {
                $quantityInput.val(currentValue + step);
            } else {
                $quantityInput.val(currentValue - step);
            }
        });
    });
</script>
<?php
return ob_get_clean();

This section generates the HTML markup for the quantity input field along with the associated JavaScript code. The output is captured using output buffering, starting with “ob_start() “and collected with “ob_get_clean()”.

The HTML markup consists of a container with the class “add-to-cart-quantity” that encapsulates three elements:

1. A minus button represented by “<button class=”minus-button”>-</button>.”

2. An input field of type “number” with class “quantity” and several attributes such as “step,” “min”, “max”, “name”, “value”, “title”, “size”, “pattern”, and “inputmode”. The value of the input field is set to the retrieved “$product_quantity”, representing the current quantity in the cart for the specified product.

3. A plus button represented by “<button class=”plus-button”>+</button>”.

The embedded JavaScript code utilizes jQuery to add event listeners to the plus and minus buttons within the “add-to-cart-quantity” container. When these buttons are clicked, the corresponding quantity value is incremented or decremented based on the step value defined in the input field.

Return and Cleanup

return ob_get_clean();

At this stage, the output buffer contains the complete HTML markup and JavaScript code generated above. The function returns the content of the output buffer using “ob_get_clean()”.

This ensures that the shortcode function returns the HTML markup, which will be inserted into the post or page where the Product Quantity Input shortcode is used.

Shortcode Registration

add_shortcode('add_to_cart_quantity', 'add_to_cart_quantity_shortcode');

The final step is to register the Product Quantity Input shortcode “add_to_cart_quantity” and associate it with the “add_to_cart_quantity_shortcode” function. The “add_shortcode” function is used for this purpose.

Once this code is added to a WordPress theme’s “functions.php” file or a custom plugin, you can use the “[add_to_cart_quantity]” shortcode in any post, page, or widget to display the quantity input field with plus and minus buttons for the specified product.

Product Quantity Input shortcode

The Product Quantity Input shortcode will also interact with the shopping cart, adjusting the quantity of the product being added or removed.

CSS Code Product Quantity Input shortcode

.add-to-cart-quantity {
        display: inline-flex;
}
 button.minus-button {
        border-radius: 50px 0px 0px 50px ;
	font-size: 21px ;
        font-weight: 400 ;
        border: 1px solid #000000;
        background-color: #ffffff ;
        color: #000;
}
button:focus {
        outline: 0px auto -webkit-focus-ring-color;
}
button.plus-button {
        border-radius: 0px 50px 50px 0px ;
        font-size: 21px;
        font-weight: 400;
        border: 1px solid #000000;
        background-color: #ffffff ;
        color: #000;
}
input[type=number]{
	border-radius:0px;
	
}

If you find additional information, please refer to this article on How to Create a Custom Product Quantity Input Shortcode with Plus and Minus Buttons in WordPress 2023. Codup

If you seek further information about How to Create a Custom Product Quantity Input Shortcode with Plus and Minus Buttons in WordPress 2023 or have any inquiries regarding our blog, please don’t hesitate to contact us via email at info@thinkwriteway.com

Share This Article :

Leave a Comment

What to read next