-
Notifications
You must be signed in to change notification settings - Fork 261
Related posts
scribu edited this page Sep 18, 2011
·
15 revisions
Continuing from the Basic usage tutorial, let's say that when viewing a single post, you don't want to show the connected page, but other posts connected to the same page.
First, you will have to create a function in your functions.php
theme file:
<?php
function get_related_posts( $post_id ) {
// Get the page connected to the post
$related_pages = get_posts( array(
'post_type' => 'page',
'connected_from' => $post_id,
'posts_per_page' => 1,
'suppress_filters' => false
) );
// No related posts if there's no page connecting them
if ( empty( $related_pages ) )
return array();
// Get the other posts connected to the same page, except the current post
return get_posts( array(
'post_type' => 'post',
'post__not_in' => array( $post_id ),
'connected_to' => $related_pages[0]->ID,
'nopaging' => true,
'suppress_filters' => false
) );
}
<?php
function get_related_posts( $post_id ) {
global $my_connection_type;
// Get the page connected to the post
$related_pages = $my_connection_type->get_connected( $post_id );
// No related posts if there's no page connecting them
if ( !$related_pages->have_posts() )
return array();
// Get the id of the first page
$page_id = $related_pages->posts[0]->ID;
// Get the other posts connected to the same page, except the current post
return $my_connection_type->get_connected( $page_id, array(
'post__not_in' => array( $post_id ),
) );
}
It takes a post id and returns an array of related posts.
Now that we have the logic for finding related posts, all we need to do is display them:
<?php p2p_list_posts( get_related_posts( get_queried_object_id() ) ); ?>
The above code would go in single.php