Announce the Number of Search Results
On search result pages, tells screen reader users how many results were found for their search as soon as the page loads.
Opens WPIDE on
Code
add_action( 'wp_footer', function () {
if ( ! is_search() ) {
return;
}
global $wp_query;
$count = (int) $wp_query->found_posts;
$message = $count
? sprintf( _n( '%1$s result found for "%2$s".', '%1$s results found for "%2$s".', $count ), number_format_i18n( $count ), get_search_query( false ) )
: sprintf( 'No results found for "%s".', get_search_query( false ) );
printf(
'<div id="wpide-search-status" class="screen-reader-text" role="status" aria-live="polite" style="position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);"></div><script>setTimeout(function(){var s=document.getElementById("wpide-search-status");if(s){s.textContent=%s;}},400);</script>',
wp_json_encode( $message )
);
} );
Notes
The message is read from a visually hidden live region; sighted visitors see no change.
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.