Skip to content
scribu edited this page Dec 18, 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;

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

If you call p2p_register_connection_type() directly from your functions.php file, it won't work. It needs to be placed in a function hooked to 'init', as above.

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
// Find connected pages
$connected = new WP_Query( array(
  'connected_type' => 'posts_to_pages',
  'connected_items' => 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;
?>

Note that get_queried_object_id() will only work when viewing a single post. When viewing a category archive, for example, it will return the category id, which Posts 2 Posts won't know how to handle.

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
// Find connected posts
$connected = new WP_Query( array(
  'connected_type' => 'posts_to_pages',
  'connected_items' => 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. The only difference is that we replaced 'Related pages' with 'Related posts'.