WP-Mix

A fresh mix of code snippets and tutorials

WordPress add titles to post navigation links

In this post, we add title attributes to WordPress post-navigation links, for both previous/next archive navigation and previous/next single-post navigation. These are some simple copy/paste functions that you can add directly to your theme (or via plugin).

Add titles to archive navigation links

The WordPress tag for displaying next navigation links is next_posts_link(). By default, it does not include a title attribute. Here is a simple function that can be used to filter the link and add a title:

function shapeSpace_next_posts_link_attributes($attr) {
	
	$attr = 'title="Previous posts"';
	
	return $attr;
	
}
add_filter('next_posts_link_attributes', 'shapeSpace_next_posts_link_attributes');

Similarly, the WordPress tag for displaying previous navigation links is previous_posts_link(). By default, it does not include a title attribute. Here is a parallel function that can be used to filter the link and add a title:

function shapeSpace_previous_posts_link_attributes($attr) {
	
	$attr = 'title="Newer posts"';
	
	return $attr;
	
}
add_filter('previous_posts_link_attributes', 'shapeSpace_previous_posts_link_attributes');

You can add both of these functions via your theme’s functions.php file, or incorporate them via simple user plugin. Then customize the title attribute as desired. You can even add other attributes as needed. Experiment and have some fun with it.

Add titles to single-post navigation links

Just like with archive nav links, single-post nav links do not include title attributes. To add them, you can use the following functions. This first function filers the output of next_post_link(), and uses the Post Title as the value of the link’s title attribute:

function shapeSpace_next_post_link($link) {
	
    global $post;
    
    $post = get_post($post_id);
    $next_post = get_next_post();
    $title = $next_post->post_title;
    $link = str_replace('rel=', 'title="'. $title .'" rel=', $link);
    
    return $link;
    
}
add_filter('next_post_link', 'shapeSpace_next_post_link');

Here is a parallel function that filters the output of previous_post_link() and likewise uses the Post Title as the value of the link’s title attribute:

function shapeSpace_previous_post_link($link) {
	
    global $post;
    
    $post = get_post($post_id);
    $previous_post = get_previous_post();
    $title = $previous_post->post_title;
    $link = str_replace('rel=', 'title="'. $title .'" rel=', $link);
    
    return $link;
    
}
add_filter('previous_post_link', 'shapeSpace_previous_post_link');

No editing is required for any of these custom functions to work. You may, however, wish to modify the output and other details to suit your needs. Also check out the links below for in-depth coverage of WP’s post-navigation functions.

Resources

Learn more

Digging Into WordPressWordPress Themes In DepthWizard’s SQL Recipes for WordPress