Add Snippet To Project
<?php
/**
* Plugin Name: Custom Qty for WooCommerce
* Description: Customize the quantity field in WooCommerce.
* Version: 1.0.0
* Author: Your Name
* Author URI: Your Website
* Text Domain: wpturbo
*/
// Add custom quantity field to WooCommerce product page
function wpturbo_custom_qty_field() {
echo '<div class="quantity">';
echo '<label for="qty">' . esc_html__('Qty', 'wpturbo') . '</label>';
echo '<input type="number" id="qty" class="input-text qty" step="1" min="1" max="" name="quantity" value="1" title="' . esc_attr__('Qty', 'wpturbo') . '" size="4" pattern="[0-9]*" inputmode="numeric" />';
echo '</div>';
}
add_action('woocommerce_before_add_to_cart_button', 'wpturbo_custom_qty_field');
// Update add to cart button text
function wpturbo_custom_add_to_cart_text($text) {
return esc_html__('Add to Cart', 'wpturbo');
}
add_filter('woocommerce_product_single_add_to_cart_text', 'wpturbo_custom_add_to_cart_text');
// Update add to cart button text for archive pages
function wpturbo_custom_add_to_cart_text_archive($text) {
return esc_html__('Select options', 'wpturbo');
}
add_filter('woocommerce_product_add_to_cart_text', 'wpturbo_custom_add_to_cart_text_archive');
// Update cart item quantity in the cart and mini cart
function wpturbo_update_cart_item_quantity($quantity, $cart_item_key) {
// Do any custom logic here
return $quantity;
}
add_filter('woocommerce_cart_item_quantity', 'wpturbo_update_cart_item_quantity', 10, 2);
Explanation:
This code is a WordPress plugin that customizes the quantity field in WooCommerce. It adds a custom quantity field to the product page, updates the 'Add to Cart' button text, and modifies the cart item quantity in the cart and mini cart.
The wpturbo_custom_qty_field() function adds a custom quantity field to the WooCommerce product page using the woocommerce_before_add_to_cart_button action hook. It creates a <div> container with a label and an <input> field for the quantity. The esc_html__() function is used to translate the label and input field placeholders.
The wpturbo_custom_add_to_cart_text() function updates the 'Add to Cart' button text on the single product page using the woocommerce_product_single_add_to_cart_text filter hook. It returns the translated text using the esc_html__() function.
The wpturbo_custom_add_to_cart_text_archive() function updates the 'Add to Cart' button text on archive pages (e.g., shop page) using the woocommerce_product_add_to_cart_text filter hook. It returns the translated text using the esc_html__() function.
The wpturbo_update_cart_item_quantity() function modifies the cart item quantity in the cart and mini cart using the woocommerce_cart_item_quantity filter hook. You can add custom logic inside this function to handle any specific requirements you have for updating the quantity.
Remember to save this code in a file named 'wp-plugin.php' and place it in the 'wp-content/plugins' directory of your WordPress installation.