Add css classes to WordPress posts links generated by next_post_link and previous_post_link functions

You might have across a situation where you needed to add css class to the html markup generated by WordPress posts links’ functions of next_post_link and previous_post_link. Especially if you working with Bootstrap or Zurb foundation frameworks as these two frameworks require specific css classes for formatting. So have come across similar situation and we found out that there are filters which we can use to add css class to WordPress posts links.

next_post_link and previous_post_link filters

The filter for next_post_link is next_post_link and filter for the previous_post_link is previous_post_link. Using these two filters we can add css class of our own choice to the link tags generated by next_post_link and previous_post_link functions. Following is an example of using these two filters to add Bootstrap specific css class to next and previous posts’ links.

add_filter('next_post_link', 'thememates_post_link_handler');
add_filter('previous_post_link', 'thememates_post_link_handler');
    
function jestem_post_link_attributes($output) {
    $code = 'class="btn btn-primary btn-filled"'; //bootstrap specific css classes we want to add
    return str_replace('<a href=', '<a '.$code.' href=', $output);
}

You can define separate functions for both the filters if you need to add different classes for both next and previous links. Following is an example of defining separate classes for both filters:

// Filter function for next_post_link
add_filter('next_post_link', 'thememates_next_post_link_handler');

function jestem_next_post_link_attributes($output) {
    $code = 'class="btn btn-primary btn-filled"'; //bootstrap specific css classes we want to add
    return str_replace('<a href=', '<a '.$code.' href=', $output);
}

// Filter function for previous_post_link
add_filter('previous_post_link', 'thememates_previous_post_link_handler');

function jestem_previous_post_link_attributes($output) {
    $code = 'class="btn btn-primary btn-filled"'; //bootstrap specific css classes we want to add
    return str_replace('<a href=', '<a '.$code.' href=', $output);
}

Comment

There is no comment on this post. Be the first one.

Leave a comment