Skip to content

Looping The Loop

scribu edited this page May 17, 2011 · 23 revisions

Continuing from the Basic usage tutorial, let's say that you want to display the connected pages, not just for a single post, but for all posts in an archive.

You would open up your theme's archive.php or loop.php or wherever you have a loop and do something like this:

<?php
p2p_each_connected( 'to', 'pages', array(
	'post_type' => 'page',
	'nopaging' => true,
) );
?>

This does an efficient query, which finds the connected pages for each post.

Now, all that's left is to display the connected pages within The Loop:

<?php while ( have_posts() ) : the_post(); ?>

	<?php if ( !empty( $post->connected_pages ) ) { ?>
		<h5>Connected Pages:</h5>
		<ul>
		<?php
		foreach ( $post->connected_pages as $post ) {
			setup_postdata( $post );

			echo '<li>';
			the_title();
			echo '</li>';
		}

		wp_reset_postdata();
		?>
		</ul>
	<?php } ?>

	... rest of code in The Loop ...

<?php endwhile; ?>
Clone this wiki locally