Add class to links generated by WordPress “next_post_link” and “previous_post_link” functions

While I was working on my Crisp Persona WordPress theme, I ran into a situation where I needed to add a class to the “Next” and “Previous” links that WordPress places at the bottom of each post (I’ll spare you the details of why I needed to do this). The links are created with a core WordPress function so the markup can’t be edited.

Update: A commenter below has shared a method of targeting these links with CSS using the “rel” attribute, which is quite a bit nicer than my original solution. You can style the links using the selectors a[rel="prev"] {} and a[rel="next."] {}. If you prefer the original method of adding a class, please read on.

I did some googling to see if they could be customized and turned up this post on Chris Coyier’s css-tricks.com site: Add class to links generated by next_posts_link and previous_posts_link. Here’s the code snippet provided there:

add_filter('next_posts_link_attributes', 'posts_link_attributes');
add_filter('previous_posts_link_attributes', 'posts_link_attributes');

function posts_link_attributes() {
  return 'class="styled-button"';
}

This works perfectly… but there’s a problem. Notice the plural “posts” in “next_posts_link_attributes”. These are the links that are displayed at the bottom of the post listings, not the ones at the bottom of individual posts. Logic says we should be able to duplicate this code with the singular forms (“next_post_link” and “previous_post_link”) and it will work. Unfortunately that’s not the case.

After a little digging through the WordPress source files, I found that the filters for the singular next and previous links are applied differently. I’ve created some code below that will add a class to the singular links:

add_filter('next_post_link', 'post_link_attributes');
add_filter('previous_post_link', 'post_link_attributes');

function post_link_attributes($output) {
    $code = 'class="styled-button"';
    return str_replace('<a href=', '<a '.$code.' href=', $output);
}