WooCommerce – How to make the product quantity input field accessible

If you wish to improve the accessibility of the WooCommerce cart page, you may need to add a label to the product quantity input. To properly associate the label with the input, the input needs an ID.

Sadly, the used function woocommerce_quantity_input doesn’t come with the option to add an ID.
The solution is pretty simple though: There is a template for this input field, which you can copy to your own theme directory and alter.

The solution:

The path of the original file is:
/wp-content/plugins/woocommerce/templates/global/quantity-input.php
Copy it to your theme folder, for example:
/wp-content/themes/mytheme/woocommerce/templates/global/quantity-input.php

Then alter it like so:

<label for="<?php if ( isset($input_id) ) { echo esc_attr( $input_id ); } else { echo 'cartquantity'; }?>" class="screen-reader-text">
  <?php _e( 'Quantity', 'woocommerce' ); ?>
</label>

<input type="number" step="<?php echo esc_attr( $step ); ?>" min="<?php echo esc_attr( $min_value ); ?>" max="<?php echo esc_attr( $max_value ); ?>" name="<?php echo esc_attr( $input_name ); ?>" value="<?php echo esc_attr( $input_value ); ?>" title="<?php echo esc_attr_x( 'Qty', 'Product quantity input tooltip', 'woocommerce' ) ?>" class="input-text qty text" size="4" pattern="<?php echo esc_attr( $pattern ); ?>" inputmode="<?php echo esc_attr( $inputmode ); ?>"
id="<?php if ( isset($input_id) ) { echo esc_attr( $input_id ); } else { echo 'cartquantity'; }
?>" />

 

Now you can pass an ID to the input field by adding the argument input_id to the woocommerce_quantity_input function:

$product_quantity = woocommerce_quantity_input( array(
  'input_name' => "cart[{$cart_item_key}][qty]",
  'input_value' => $cart_item['quantity'],
  'max_value' => $_product->backorders_allowed() ? '' : $_product->get_stock_quantity(),
  'min_value' => '0',	
  'input_id' => "cart[{$cart_item_key}][qty]"
), $_product, false );

 

Why did you have to go and make things so complicated?

You may wonder why I used a variable for the ID. The reason for this is the cart page: Here you may have multiple products, which all have this quantity input field next to them. If we used a simple string as an ID, we would have multiple elements with the same ID, which is not semantically correct HTML and hinders screen readers from finding the correct input to associate the label with.

 

Thanks to Kathy aka helgatheviking for the helpful comment which led me to this solution.