Automattic\WooCommerce\Blocks\BlockTypes

AddToCartForm::add_steppersprivateWC 1.0

Add increment and decrement buttons to the quantity input field.

Method of the class: AddToCartForm{}

No Hooks.

Returns

String. Add to Cart form HTML with increment and decrement buttons.

Usage

// private - for code of main (parent) class only
$result = $this->add_steppers( $product_html, $product_name );
$product_html(string) (required)
Add to Cart form HTML.
$product_name(string) (required)
Product name.

AddToCartForm::add_steppers() code WC 10.8.1

private function add_steppers( $product_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" class="wc-block-components-quantity-selector__button wc-block-components-quantity-selector__button--plus">+</button>';
		},
		$product_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" class="wc-block-components-quantity-selector__button wc-block-components-quantity-selector__button--minus">−</button>';
		},
		$new_html ?? ''
	);
	return $new_html ?? '';
}