Hello, I'm Chris Murphy — I specialize in creating engaging, user-centric interactive experiences.
Enhancing The Previous & Next Links in WordPress 3.0
The “previous post” and “next post” links that appear in your WordPress templates can be quite handy when navigating between posts, but for the most part the output of get_next_post_link() and get_previous_post_link() are quite limited.
Instead of going through all of the hassle to hack out new functionality to support an existing feature, we can rely on existing functionality within WordPress’ core to extend the feature. In this case, we can take advantage of WordPress’ underrated get_adjacent_post() function, which you can find in the link-template.php
Fig. 1 The image above is an example of the feature enhancement in action.
WordPress’ get_adjacent_post() Function
The function, get_adjacent_post() has been around since WordPress 2.5, but despite it’s availability, I’ve seen a number of hacks that come in the form of bloated plug-in files and unnecessary SQL Queries (using WP_Query).
With all of the great upgrades that WordPress has received with the 3.0 release, it’s too bad that some of the core features didn’t receive additional treatment–but then again, I suppose that an update to a function like get_adjacent_post() wouldn’t make much sense and would likely break backwards functionality (and not to mention that WordPress is intended to be extensible.)
With that in mind, let’s take a look at how we can extend a core feature like get_adjacent_post().
The getPostNavigation() Function
Using get_adjacent_post() we are able to retrieve the previous and next post easily, but the real benefit comes in the fact that we’re retrieving all of the data associated with that post: Post Title, Post Content, Post Excerpt, Post Permalink, etc.
Note: There exists two other function calls that go unnoticed by the majority of theme developers: get_previous_post(), and get_next_post(). Both of these utility functions use get_adjacent_post(), but these are really just vanity methods for get_adjacent_post()–we want to go straight to the original method.
Goals of this function:
- Get the Previous, Next, and Current Post with one function call
- Get a well-formatted unordered list
- Extensibility
/**
* Get either the current, previous or next post in an unordered list structure.
* @param String $post_position The post position: "previous" = previous post, "next" = next post, "current" = current post.
* @param Bool $showpermalink Show or hide the permalink in the post title (typically used only for the previous and next posts)
* @param Array $classes An array of classes to be applied to the unordered list
* @return string The previous or next post formatted in an unordered list that can be styled
*/
function getPostNavigation( $post_position = 'previous', $showpermalink = false, $classes = array() )
{
try
{
$objPost;
$classes[] = 'post-navi';
switch( $post_position )
{
case 'next' :
$objPost = get_adjacent_post( false, '', false );
$classes[] = 'next-post';
break;
case 'current' :
global $post;
$objPost = $post;
$classes[] = 'current-post';
break;
case 'previous' :
default:
$objPost = get_adjacent_post( false, '',true );
$classes[] = 'prev-post';
break;
}
if( empty( $objPost ) ) return;
// The title with additional formatting applied
// TODO: Apply your own formatting, truncation, etc.
$title = htmlentities( $title );
// An HTML safe string to be used with the tooltip
$tooltip = ( $post_position != 'current' ) ? "View Post: "" . $title . """ : """ . $title . """;
// Standard elements, heading, permalink, and excerpt
$heading = ( $post_position != 'current' ) ? '<a href="' . get_permalink( $objPost->ID ) . '" title="' . $tooltip . '">' . $title . '</a>' : $title;
$permalink = '<a href="' . get_permalink( $objPost->ID ) . '" title="' . $tooltip . '">Read More</a>';
$excerpt = trim( strip_tags( $objPost->post_content ) ) ;
// The formatted output
$output = "<ul class=\"" . implode(' ', $classes) . "\">\r\n";
$output .= "<li class=\"post-navi-heading\">{$heading}</li>\r\n";
$output .= "<li class=\"post-navi-excerpt\">{$excerpt}</li>\r\n";
$output .= ( $showpermalink == true ) ? "<li class=\"post-navi-permalink\">{$permalink}</li>\r\n" : '';
$output .= "</ul>\r\n";
}
catch( Exception $err )
{
throw new Exception( $err->getMessage() );
}
return $output;
}
Example Usage
if( function_exists( getPostNavigation ) )
{
$prev_post_ul = getPostNavigation( 'previous', true, array( 'your-custom-class', 'another-class', 'one-more-class' ) );
$curr_post_ul = getPostNavigation( 'current', false, array( 'link-list', 'col', 'one-col' ) );
$next_post_ul = getPostNavigation( 'next', true, array( 'link-list', 'col', 'one-col', 'last' ) );
}
<!-- SET: POST NAVIGATION -->
<div>
<?php echo $prev_post_ul; ?>
<?php echo $curr_post_ul; ?>
<?php echo $next_post_ul; ?>
</div>
<!-- END: POST NAVIGATION -->
Like the get_previous_post_link() and the get_next_post_link(), we can use the function’s output wherever we want in our template, giving us the flexibility to fit the output into simple or complex layouts.
The Breakdown
$objPost;
$classes[] = 'post-navi';
switch( $post_position )
{
case 'next' :
$objPost = get_adjacent_post( false, '', false );
$classes[] = 'next-post';
break;
case 'current' :
global $post;
$objPost = $post;
$classes[] = 'current-post';
break;
case 'previous' :
default:
$objPost = get_adjacent_post( false, '',true );
$classes[] = 'prev-post';
break;
}
All of the magic really happens in the Switch statement. It is here that we condition the get_adjacent_post() function to retrieve the previous and next post–but for the current post data, we simply use the readily available $post variable.
Note: In order to use the $post variable in any function, it’s scope must be declared using the “global” keyword.
The Switch statement is also used to add three additional CSS classes to the unordered list that can be used for custom styling if you want to use the functions’ defaults. These three classes allow for distinction amongst the expected output:
- next-post
- prev-post
- current-post
The Output
The output itself is pretty straight-forward: we’re slugging various fields of the previous, next, or current post into an unordered list that we can style with CSS; here is an example:
$output = "<ul class=\"" . implode(' ', $classes) . "\">\r\n";
$output .= "<li class=\"post-navi-heading\">{$heading}</li>\r\n";
$output .= "<li class=\"post-navi-excerpt\">{$excerpt}</li>\r\n";
$output .= ( $showpermalink == true ) ? "<li class=\"post-navi-permalink\">{$permalink}</li>\r\n" : '';
$output .= "</ul>\r\n";
Extending getPostNavigation()
As usual, this function will need to be placed in your functions.php file, but you shouldn’t stop there—the output can be structured however you need it. Customization for your particular needs can be accomplished by simply replacing the html markup in the function with your own.
![]()
Comments on This Post:
Add a Comment:
Comment Guidelines: Basic XHTML is allowed (a href, strong, em, code). All line breaks and paragraphs are automatically generated. Off-topic or inappropriate comments will be edited or deleted. Email addresses will never be published. Keep it PG-13 people!
XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


online MBA
Date: July 22, 2011
Time: 1:57 am
How do i edit the main index for my site using word press 3.0? I get into site admin and appearance. But when I put something into the template and hit save nothing happens. I can even delete all the text in the main index and hit save, and still nothing changes.
Dusty Lyberg…
Date: December 16, 2011
Time: 5:55 pm
Distracted driving was the cause of more than 3,000 deaths in 2010. So lets put down the phones while driving!
alban
Date: December 19, 2011
Time: 8:30 am
Nice stuf thnx for share
i’ve updated my web Alba Media
gameloo
Date: December 22, 2011
Time: 11:35 pm
Thanks for the code. Apparently, there is a plugin in the WP extension directory to do this ‘Previous and Next’ with title tag.
Related site…
Date: October 14, 2012
Time: 12:43 am
I’m not sure where you’re getting your info, but good topic.
I needs to spend some time learning more or understanding more.
Thanks for magnificent info I was looking for this
information for my mission.
Erick
Date: November 11, 2012
Time: 12:23 pm
I visited many blogs however the audio quality for audio songs existing at this website is truly wonderful.
asphalt cont…
Date: December 26, 2012
Time: 8:23 am
Having read this I thought it was rather enlightening.
I appreciate you spending some time and energy to put this short article together.
I once again find myself spending a lot of time both reading and commenting.
But so what, it was still worthwhile!
how to creat…
Date: March 5, 2013
Time: 5:22 pm
I do not know if it’s just me or if everyone else experiencing problems with your site. It seems like some of the text in your posts are running off the screen. Can somebody else please provide feedback and let me know if this is happening to them as well? This could be a issue with my web browser because I’ve had this happen before.
Appreciate it
black samsun…
Date: April 29, 2013
Time: 9:29 am
Hey there I am so thrilled I found your site, I really found you
by accident, while I was looking on Digg for something else, Anyways I am
here now and would just like to say thanks for a fantastic post and a all
round interesting blog (I also love the theme/design), I don’t have time to read it all at the minute but I have saved it and also added your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the great job.