Skip to content
scribu edited this page Sep 20, 2011 · 51 revisions

In the following tutorial we will be creating connections between posts and pages and then displaying them in various ways.

Registering a connection type

The first thing you'll want to do is register a connection type. This will add a nice connection box to the post editing screen.

In your theme's functions.php file, add:

<?php
function my_connection_types() {
	// Make sure the Posts 2 Posts plugin is active.
	if ( !function_exists( 'p2p_register_connection_type' ) )
		return;

	// Keep a reference to the connection type; we'll need it later
	global $my_connection_type;

	$my_connection_type = p2p_register_connection_type( array(
		'from' => 'post',
		'to' => 'page'
	) );
}
add_action( 'init', 'my_connection_types', 100 );
?>

Go to the admin area and create a few connections.

Displaying connected pages

Now, you will probably want to display these connections somewhere.

The next block of code will display a list of pages that are connected from the current post. Add it to your theme's single.php file:

<?php
global $my_connection_type;

// Find connected pages
$connected = $my_connection_type->get_connected( get_queried_object_id() );

// Display connected pages
if ( $connected->have_posts() ) :
?>
<h3>Related pages:</h3>
<ul>
<?php while ( $connected->have_posts() ) : $connected->the_post(); ?>
	<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>

<?php 
// Prevent weirdness
wp_reset_postdata();

endif;
?>

Displaying connected posts

We can also do the opposite: display posts that connect to the current page. The following code goes in your theme's page.php file:

<?php
global $my_connection_type;

// Find connected posts
$connected = $my_connection_type->get_connected( get_queried_object_id() );

// Display connected posts
if ( $connected->have_posts() ) :
?>
<h3>Related posts:</h3>
<ul>
<?php while ( $connected->have_posts() ) : $connected->the_post(); ?>
	<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>

<?php 
// Prevent weirdness
wp_reset_postdata();

endif;
?>

You can see the code is almost identical.

Using p2p_list_posts()

If you just want to display a simple list of post links, you can use p2p_list_posts():

<?php
global $my_connection_type;

// Find connected posts
$connected = $my_connection_type->get_connected( get_queried_object_id() );

// Display connected posts
if ( $connected->have_posts() ) :
	echo '<h3>Related posts</h3>';
	p2p_list_posts( $connected );
endif;
?>