Skip to content

Get adjacent items

scribu edited this page Mar 10, 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 the get_adjacent_items() method 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 the following example we have linked many posts to one series. We set up our connection type like so:

<?php

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``
		'cardinality' => 'many-to-one', //optional
	) );
}
add_action( 'p2p_init', 'my_connection_types' );

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 );

if ( $items['parent'] )
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'] );
?>