Sag Rising

Notes to Myself

Creating Next and Previous Post Links

Posted by Richard Cockrum on March 15, 2008

I love it when I'm able to learn something new, no matter how trivial it may seem. The most recent new thing I learned is how to put the next and previous post links at the top of individual post pages. This may not be the best way to do it, but it does work.

What I did was create two functions in my theme file.

public function next_post_link( $post )
{
	$next_link = '';
	$next_post= false;
	DB::set_fetch_mode( PDO::FETCH_CLASS );
	DB::set_fetch_class( 'Post' );
	
        $next_post= 
		DB::get_row( 'select * from {posts} where 
                 content_type = ? and status = ? and pubdate > ? 
                 order by pubdate asc', 
                 array(Post::type('entry'), 
                 Post::status('published'), 
                 $post->pubdate), 'Post' );

		if( ( $next_post ) != false ) {
			$next_link= '<a href="' . 
                        $next_post->permalink. '" title="' . 
                        $next_post->title .'" >' . 
                        $next_post->title . ' & raquo ;</a>';
		}

	return $next_link;
}

public function prev_post_link( $post )
{
	$prev_link = '';
	$prev_post= false;
	DB::set_fetch_mode( PDO::FETCH_CLASS );
	DB::set_fetch_class( 'Post' );

	$prev_post= 
       		DB::get_row( 'select * from {posts} where 
                  content_type = ? and status = ? and pubdate < ? 
                  order by pubdate desc', 
                  array(Post::type('entry'), 
                  Post::status('published'), 
                  $post->pubdate), 'Post' );

		if( ( $prev_post ) != false ) {
			$prev_link= '<a href="' . 
                        $prev_post->permalink. '" 
                        title="' . $prev_post->title .'" >' . 
                        '& laquo ; ' . 
                        $prev_post->title . '</a>';
		}

	return $prev_link;
}

As you can see, I pass the functions the current post, do a select on the posts table in the database to get the exact post I want, then build a link from the post's properties. The most difficult part of getting these to work was that, even though I was only getting one post, I still had to give the database an order by clause to get the posts sorted properly before the post I wanted was selected.

As a note, remove the spaces around laquo and raquo if you use this code. I couldn't get the actual code to display and not the symbols they stand for without the spaces.

This isn't the most general way to select a post with a position relative to another post, but it works and is fairly fast, with little unneeded information travelling over the network.

This entry is filed under , and . You can follow any responses to this entry through the feed . New comments are currently closed.

What do you think?
Comments for this post are disabled.