Skip to content

Get adjacent items

dawnbuie edited this page Mar 9, 2013 · 7 revisions

Often we want to create navigation links to the next and previous post in a series and the series itself. This is what get_adjacent_items() function does; given the ID of the current post it returns the WP_Post objects for the previous and next sibling posts, if they exist and for the parent series.

In this example we have linked many posts to one series. We set up our post relationships in functions.php like so:

function my_connection_types() {
	p2p_register_connection_type( array(
		'name' => 'post_to_series', 
		'from' => 'post',
		'to' => 'series',
		'sortable' => 'any',  // this must be set to 'any' or ``true`` for get_adjacent_items() 
		'cardinality' => 'many-to-one', //optional
	) );
}

Then we add the following to our single.php template to affect posts that are connected to a series.

<?php
$items = p2p_type('posts_to_series')->get_adjacent_items( $episode_id );

echo '<br> parent: '. get_permalink( $items['parent'] ); 

if ( $items['previous'] )
echo '<br> previous: ' . get_permalink( $items['previous'] );

if ( $items['next'] )
echo '<br> next: ' . get_permalink( $items['next'] );
?>

Clone this wiki locally