如何为WooCommerce商品页数量输入框添加单位标识(kg/tk)并实现加减按钮调节功能?
Hey there! Let's tackle this WooCommerce quantity input issue with units (kg/tk) that you're facing. I've got two solid solutions for you—one with custom code (total control) and another with plugins (quick setup). Let's dive in!
Solution 1: Custom Code (Full Flexibility)
This approach lets you add per-product unit selection, modify the quantity input to show units, and handle both button clicks and manual input with units.
Step 1: Add a Unit Selector to Product Edit Page
First, we'll add a dropdown in the product's general settings so you can pick kg or tk for each product:
// Add product unit selector in admin add_action( 'woocommerce_product_options_general_product_data', 'add_product_unit_selector' ); function add_product_unit_selector() { woocommerce_wp_select( array( 'id' => '_custom_product_unit', 'label' => __( 'Product Unit', 'your-text-domain' ), 'options' => array( '' => __( 'Select a unit', 'your-text-domain' ), 'kg' => __( 'kg (Kilogram)', 'your-text-domain' ), 'tk' => __( 'tk (Piece)', 'your-text-domain' ), ), 'desc_tip' => true, 'description' => __( 'Choose the unit to display for this product\'s quantity input.', 'your-text-domain' ), ) ); } // Save the unit selection add_action( 'woocommerce_process_product_meta', 'save_product_unit_selector' ); function save_product_unit_selector( $post_id ) { $unit = isset( $_POST['_custom_product_unit'] ) ? sanitize_text_field( $_POST['_custom_product_unit'] ) : ''; update_post_meta( $post_id, '_custom_product_unit', $unit ); }
Step 2: Replace Default Quantity Input with Custom One
Next, we'll override the default quantity input to include plus/minus buttons and the selected unit:
// Custom quantity input with unit and buttons add_filter( 'woocommerce_quantity_input_html', 'custom_quantity_input_with_unit', 10, 3 ); function custom_quantity_input_with_unit( $html, $product, $args ) { $unit = get_post_meta( $product->get_id(), '_custom_product_unit', true ); if ( empty( $unit ) ) return $html; $min = $args['min_value']; $max = $args['max_value']; $step = $args['step']; $value = $args['input_value']; // Build custom input HTML $html = '<div class="custom-quantity-wrapper">'; $html .= '<button type="button" class="qty-btn qty-minus" data-step="' . esc_attr( $step ) . '">-</button>'; $html .= '<input type="text" name="quantity" value="' . esc_attr( $value ) . ' ' . esc_attr( $unit ) . '" class="qty-input" min="' . esc_attr( $min ) . '" max="' . esc_attr( $max ) . '" step="' . esc_attr( $step ) . '" />'; $html .= '<button type="button" class="qty-btn qty-plus" data-step="' . esc_attr( $step ) . '">+</button>'; $html .= '</div>'; return $html; }
Step 3: Add JavaScript for Button & Input Handling
This JS will handle plus/minus clicks, ensure the unit stays visible, and strip the unit from the value when the form submits (WooCommerce only needs the numeric quantity):
jQuery(document).ready(function($) { // Handle plus/minus buttons $(document).on('click', '.qty-btn', function() { const $input = $(this).siblings('.qty-input'); const step = parseFloat($(this).data('step')); const unitMatch = $input.val().match(/[a-zA-Z]+$/); const unit = unitMatch ? unitMatch[0] : ''; let currentVal = parseFloat($input.val().replace(/[^0-9.]/g, '')); // Get numeric value if (isNaN(currentVal)) currentVal = parseFloat($input.attr('min')) || 0; if ($(this).hasClass('qty-minus')) { currentVal = Math.max(currentVal - step, parseFloat($input.attr('min')) || 0); } else { currentVal = Math.min(currentVal + step, parseFloat($input.attr('max')) || Infinity); } $input.val(`${currentVal} ${unit}`); }); // Clean up input on blur (ensure unit is present) $(document).on('blur', '.qty-input', function() { const $input = $(this); const productId = $input.closest('.product').data('product_id'); const unit = productId ? get_post_meta(productId, '_custom_product_unit', true) : ''; let val = $input.val().replace(/[^0-9.]/g, ''); if (val === '') val = parseFloat($input.attr('min')) || 0; $input.val(`${val} ${unit}`); }); // Strip unit before form submission $(document).on('submit', 'form.cart', function() { const $qty = $(this).find('.qty-input'); const numericVal = $qty.val().replace(/[^0-9.]/g, ''); $qty.val(numericVal); }); });
Step 4: Add CSS for Styling
Make the custom input look clean and aligned:
.custom-quantity-wrapper { display: flex; align-items: center; gap: 0.5rem; margin: 1rem 0; } .qty-btn { padding: 0.3rem 0.6rem; border: 1px solid #ddd; background: #f8f8f8; cursor: pointer; transition: background 0.2s; } .qty-btn:hover { background: #e8e8e8; } .qty-input { width: 80px; text-align: center; padding: 0.3rem; border: 1px solid #ddd; }
How to Use This Code:
- Add the PHP code to your child theme's
functions.phpfile, or use a plugin like Code Snippets to avoid losing changes when updating your theme. - Add the JS to your theme's
footer.php(before the closing</body>tag) or use the WordPress customizer's "Additional JS" section. - Add the CSS to your theme's customizer "Additional CSS" section.
Solution 2: Plugin-Based Approach (No Code Needed)
If you prefer not to write code, these plugins can solve your issue:
- Advanced Quantity for WooCommerce: Lets you set per-product units, quantity steps, min/max values, and displays the unit next to the quantity input. It works with plus/minus buttons and supports manual input with units.
- WooCommerce Custom Quantity Fields: Offers per-product unit configuration, and you can easily integrate it with your existing WPC Product Quantity plugin by enabling unit display in settings.
- Extend Your Existing Plugins: If you want to keep using WPC Product Quantity, copy its template file (
wp-content/plugins/wpc-product-quantity/templates/quantity-input.php) to your child theme'swoocommercefolder, then edit the template to add the unit (pulled from the custom product field we added in Solution 1).
内容的提问来源于stack exchange,提问作者Stiven Lille

