Automattic\WooCommerce\Blocks\BlockTypes\AddToCartWithOptions

Utils::add_quantity_stepperspublic staticWC 1.0

Add increment and decrement buttons to the quantity input field.

Method of the class: Utils{}

No Hooks.

Returns

String. Quantity input HTML with increment and decrement buttons.

Usage

$result = Utils::add_quantity_steppers( $quantity_html, $product_name );
$quantity_html(string) (required)
Quantity input HTML.
$product_name(string) (required)
Product name.

Utils::add_quantity_steppers() code WC 10.9.4

public static function add_quantity_steppers( $quantity_html, $product_name ) {
	// Regex pattern to match the <input> element with id starting with 'quantity_'.
	$pattern = '/(<input[^>]*id="quantity_[^"]*"[^>]*\/>)/';
	// Replacement string to add button AFTER the matched <input> element.
	// Use preg_replace_callback to avoid backreference interpretation of $, \ sequences in product names.
	$new_html = preg_replace_callback(
		$pattern,
		function ( $matches ) use ( $product_name ) {
			/* translators: %s refers to the item name in the cart. */
			$plus_aria = esc_attr( sprintf( __( 'Increase quantity of %s', 'woocommerce' ), $product_name ) );
			return $matches[1] . '<button aria-label="' . $plus_aria . '" type="button" data-wp-on--click="actions.increaseQuantity" data-wp-bind--disabled="!state.allowsIncrease" class="wc-block-components-quantity-selector__button wc-block-components-quantity-selector__button--plus">+</button>';
		},
		$quantity_html ?? ''
	);
	$new_html = preg_replace_callback(
		$pattern,
		function ( $matches ) use ( $product_name ) {
			/* translators: %s refers to the item name in the cart. */
			$minus_aria = esc_attr( sprintf( __( 'Reduce quantity of %s', 'woocommerce' ), $product_name ) );
			return $matches[1] . '<button aria-label="' . $minus_aria . '" type="button" data-wp-on--click="actions.decreaseQuantity" data-wp-bind--disabled="!state.allowsDecrease" class="wc-block-components-quantity-selector__button wc-block-components-quantity-selector__button--minus">−</button>';
		},
		$new_html ?? ''
	);
	return $new_html ?? '';
}