Give Theme Search Forms an Accessible Label
Adds an accessible name to the search field of theme search forms that have no label, so screen reader users hear "Search" instead of an unlabeled text field.
Opens WPIDE on
Code
// Accessible name for the search field.
$wpide_search_label = 'Search this site';
add_filter( 'get_search_form', function ( $form ) use ( $wpide_search_label ) {
if ( false !== stripos( $form, '<label' ) || ! class_exists( 'WP_HTML_Tag_Processor' ) ) {
return $form;
}
$tags = new WP_HTML_Tag_Processor( $form );
while ( $tags->next_tag( 'input' ) ) {
if ( ( 's' === $tags->get_attribute( 'name' ) || 'search' === $tags->get_attribute( 'type' ) ) && ! $tags->get_attribute( 'aria-label' ) ) {
$tags->set_attribute( 'aria-label', $wpide_search_label );
}
}
return $tags->get_updated_html();
}, 20 );
Notes
Change $wpide_search_label to translate the label.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.