WooCommerce Quantity

Home » Snippets » WooCommerce Quantity
0

Created with:

Visibility: 

public

Creator: Seth

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project
					<?php

/**
 * Plugin Name: Your WP Plugin
 * Author: WP Turbo
 * Author URI: https://wpturbo.dev
 * Version: 1.0.0
 * Description: Add "-" on the left side and "+" on the right side of the quantity field on WooCommerce with custom styling.
 * Text Domain: wpturbo
 */

// Add "-" and "+" buttons to quantity field on WooCommerce product page
function wpturbo_add_quantity_buttons() {
    echo '<div class="quantity">';
    echo '<button type="button" class="minus" onclick="wpturbo_update_quantity(-1)">-</button>';
    echo '<input type="number" class="input-text qty text" step="1" min="1" max="" name="quantity" value="1" title="Qty" size="4" pattern="[0-9]*" inputmode="numeric">';
    echo '<button type="button" class="plus" onclick="wpturbo_update_quantity(1)">+</button>';
    echo '</div>';
}

// Enqueue custom stylesheet for styling the quantity buttons
function wpturbo_enqueue_styles() {
    wp_enqueue_style( 'wpturbo-styles', plugin_dir_url( __FILE__ ) . 'css/styles.css' );
}

// Add custom JavaScript to handle quantity updates
function wpturbo_enqueue_scripts() {
    wp_enqueue_script( 'wpturbo-script', plugin_dir_url( __FILE__ ) . 'js/script.js', array( 'jquery' ), '1.0.0', true );
}

// Register hooks
add_action( 'woocommerce_before_add_to_cart_button', 'wpturbo_add_quantity_buttons', 10 );
add_action( 'wp_enqueue_scripts', 'wpturbo_enqueue_styles' );
add_action( 'wp_enqueue_scripts', 'wpturbo_enqueue_scripts' );

// JavaScript function to update quantity
function wpturbo_update_quantity( value ) {
    var quantityInput = jQuery('.quantity .qty');
    var currentQuantity = parseInt( quantityInput.val() );
    
    if ( isNaN( currentQuantity ) ) {
        currentQuantity = 0;
    }
    
    var newQuantity = currentQuantity + value;
    
    if ( newQuantity >= 1 ) {
        quantityInput.val( newQuantity );
    }
}
				

Register an account to save your snippets or go Pro to get more features.