Adding aria-labels to wp_dropdown_categories()

How to add aria-label attribute support to dropdown elements produced by wp_dropdown_categories().

For a recent project, there was a requirement to output a list of Categories in a <select> dropdown.  Typically, this could be achieved by having two elements:

  • <label for="category">Category</label>
  • wp_dropdown_categories( 'id' => 'category' ... )

For visitors using assistive technologies (screen readers, voiceover etc), the above HTML structure and relationship would make clear to them that the <select> dropdown is a list of Categories.

However, the project design required that no label be displayed.  This would fail to meet WCAG Success Criteria 4.1.2, which states:

For all user interface components (including but not limited to: form elements, links and components generated by scripts), the name and role can be programmatically determined; states, properties, and values that can be set by the user can be programmatically set; and notification of changes to these items is available to user agents, including assistive technologies. (Level A)

Thanks to WordPress’ Filter Hooks, we can add support for additional array arguments to be passed when calling wp_dropdown_categories():

To output an aria-label attribute on the <select>wp_dropdown_categories( array( 'aria-label' => __( 'Category Selection', 'n7studios' ), ... )

Interested in talking to us about your WordPress project?

Contact Us