Descriptive Labels for Previous and Next Post Links
Adds aria-labels like "Previous post: Title" to the previous and next post links in classic themes, so screen readers announce where each link leads.
Opens WPIDE on
Code
$wpide_adjacent_label = function ( $output, $format, $link, $post, $adjacent ) {
if ( ! $output || ! $post || ! class_exists( 'WP_HTML_Tag_Processor' ) ) {
return $output;
}
$tags = new WP_HTML_Tag_Processor( $output );
if ( $tags->next_tag( 'a' ) && ! $tags->get_attribute( 'aria-label' ) ) {
$prefix = 'previous' === $adjacent ? 'Previous post: ' : 'Next post: ';
$tags->set_attribute( 'aria-label', $prefix . wp_strip_all_tags( get_the_title( $post ) ) );
}
return $tags->get_updated_html();
};
add_filter( 'previous_post_link', $wpide_adjacent_label, 10, 5 );
add_filter( 'next_post_link', $wpide_adjacent_label, 10, 5 );
Notes
Block themes using the Post Navigation Link block already include the title in the link text.
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.