Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.