Accessible Pagination Labels
Gives numbered pagination links clear labels such as "Page 3" and names the pagination landmark "Posts pages", so screen reader users know what each link does.
Opens WPIDE on
Code
add_filter( 'paginate_links_output', function ( $output ) {
if ( ! $output || ! class_exists( 'WP_HTML_Tag_Processor' ) ) {
return $output;
}
$tags = new WP_HTML_Tag_Processor( $output );
while ( $tags->next_tag() ) {
if ( ! in_array( $tags->get_tag(), array( 'A', 'SPAN' ), true ) || ! $tags->has_class( 'page-numbers' ) || $tags->get_attribute( 'aria-label' ) ) {
continue;
}
if ( $tags->has_class( 'prev' ) ) {
$tags->set_attribute( 'aria-label', 'Previous page' );
} elseif ( $tags->has_class( 'next' ) ) {
$tags->set_attribute( 'aria-label', 'Next page' );
} elseif ( $tags->has_class( 'current' ) ) {
$tags->set_attribute( 'aria-label', 'Current page' );
} elseif ( 'A' === $tags->get_tag() ) {
$tags->set_attribute( 'class', trim( $tags->get_attribute( 'class' ) . ' wpide-page-link' ) );
}
}
// Numbered links get "Page N" from their text.
return preg_replace_callback( '#<a([^>]*\bwpide-page-link\b[^>]*)>([^<]*\d+[^<]*)</a>#', function ( $m ) {
$number = (int) preg_replace( '/\D+/', '', $m[2] );
return '<a' . $m[1] . ' aria-label="' . esc_attr( 'Page ' . $number ) . '">' . $m[2] . '</a>';
}, $tags->get_updated_html() );
} );
add_filter( 'navigation_markup_template', function ( $template, $class ) {
if ( 'pagination' === $class ) {
$template = str_replace( 'aria-label="%4$s"', 'aria-label="Posts pages"', $template );
}
return $template;
}, 10, 2 );
Notes
Applies to pagination built with the core paginate_links() and the_posts_pagination() functions.
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.