WP-Mix

A fresh mix of code snippets and tutorials

Add titles to previous_post_link & next_post_link

Here’s a quick way to include a title in previous_post_link() and next_post_link().

Just replace the previous_post_link() and next_post_link() tags in your theme with the following code:

<?php 
	$p = get_adjacent_post(false, '', true);
	if(!empty($p)) echo '<div class="prev"><a href="' . get_permalink($p->ID) . '" title="' . $p->post_title . '">' . $p->post_title . '</a></div>';

	$n = get_adjacent_post(false, '', false);
	if(!empty($n)) echo '<div class="next"><a href="' . get_permalink($n->ID) . '" title="' . $n->post_title . '">' . $n->post_title . '</a></div>'; 
?>

Quick rundown: with this code, we’re using get_adjacent_post() as a replacement for previous_post_link() and next_post_link(). This enables us to get the data we need to reconstruct the navigation links with the title-attributes included. The main difference between “next” and “previous” is seen in the third parameter, “true” vs “false”, in get_adjacent_post().

Learn more

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