-
Notifications
You must be signed in to change notification settings - Fork 3
Basic usage
In the following tutorial we will be creating connections between posts and pages and then displaying them in various ways.
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( 'wp_loaded', 'my_connection_types' );
?>
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.
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(),
'nopaging' => true,
) );
// 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.
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(),
'nopaging' => true,
) );
// 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'.
The above methods can be applied using the get_posts function, with one extra requirement - setting the option 'suppress_filters' to false. This is because the default get_posts setting for this is true, although using WP_Query the default is false.
E.g.
<?php
// Find connected posts
$connected = get_posts( array(
'connected_type' => 'posts_to_pages',
'connected_items' => get_queried_object_id(),
'nopaging' => true,
'supress_filters' => true
) );