-
Notifications
You must be signed in to change notification settings - Fork 261
Related posts
scribu edited this page May 11, 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 relating them
if ( empty( $related_pages ) )
return array();
// Get the other posts connected to the same page
return get_posts( array(
'post_type' => 'post',
'post__not_in' => array( $post_id ),
'connected_to' => $related_pages[0]->ID,
'nopaging' => true,
'suppress_filters' => false
) );
}
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
$related_posts = get_related_posts( get_queried_object_id() );
echo '<ul>';
foreach ( $related_posts as $post ) {
setup_postdata( $post );
echo '<li>';
the_title();
echo '</li>';
}
echo '</ul>';
wp_reset_postdata();
The above code would go in single.php