How To Customize And Add Class Or Div To WordPress Next Previous Post Links

How To Add The Default Next/Previous Links To A Post

You can place next post and previous post links within your WordPress single.php with the following code

		echo previous_post_link();
		echo next_post_link();

Adding Attributes Such As Class To The Links

This outputs the links using the posts’ titles.  If you would like to add custom attributes to the links such as class, you would add the following code to your functions.php file (replace my-custom-class with your class name).

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

function posts_link_attributes() {
    return 'class="my-custom-class"';
}

Wrapping The Links

If you would like to wrap the links in divs for greater control and positioning, you can do so through custom functions, or directly within your single.php file by using the get_adjacent_post function.  The function accepts several parameters, $in_same_term (default=false), $exluded_terms(term1,term2,etc), $previous(default=true), $taxonomy(default=category)

// Generate link to previous post as a title
$previous = get_adjacent_post('', '', true);
if(!empty($previous)) echo '<div class="prev-post">Previous Post => <a href="' . get_permalink($previous->ID) . '" title="' . $previous->post_title . '">' . $previous->post_title . '</a></div>';

// Generate link to next post as a title
$next = get_adjacent_post('', '', false);
if(!empty($next)) echo '<div class="next-post">Next Post => <a href="' . get_permalink($next->ID) . '" title="' . $next->post_title . '">' . $next->post_title . '</a></div>';

To display the links as arrows, simply modify the code by replacing the $next->post_title with arrows or FontAwesome fonts and style accordingly.

 

Available for Amazon Prime