Displaying Related Category and Author Content in Wordpress

June 17, 2008 · Print This Article

View any single-post page from a wordpress blog and you’ll notice two sidebar modules called “More from this category” and “More from this author”.

As a designer, you want to help users explore topics in a forward or sideways motion from anywhere on the site. You can accomplish this by pulling in related content and providing logical jumping-off points, without requiring users to work backward.

Here’s a simplified version of the code, which must be included outside of the loop:


<?php

//Gets category and author info
global $wp_query;
$cats = get_the_category();
$postAuthor = $wp_query->post->post_author;
$tempQuery = $wp_query;
$currentId = $post->ID;

// related author posts
$newQuery = "posts_per_page=5&author=" . $authorPosts;
query_posts( $newQuery );
$authorPosts = "";
$count = 0;
if (have_posts()) {
while (have_posts()) {
$count++;
the_post();
if( $count<4 && $currentId!=$post->ID) {
$count++;
$authorPosts .= '<li><a href="' . get_permalink() . '">' . the_title( "", "", false ) . '</a></li>';
}
}
}

// related category posts
$catlist = "";
forEach( $cats as $c ) {
if( $catlist != "" ) { $catlist .= ","; }
$catlist .= $c->cat_ID;
}
$newQuery = "posts_per_page=5&cat=" . $catlist;
query_posts( $newQuery );
$categoryPosts = "";
$count = 0;
if (have_posts()) {
while (have_posts()) {
the_post();
if( $count<4 && $currentId!=$post->ID) {
$count++;
$categoryPosts .= '<li><a href="' . get_permalink() . '">' . the_title( "", "", false ) . '</a></li>';
}
}
}
$wp_query = $tempQuery;
?>Then inside the loop, call the functions like this:

<h4>More from this category</h4>
<ul>
<?php echo $categoryPosts; ?>
</ul>

<h4>More from this author</h4>
<ul>
<?php echo $authorPosts; ?>
</ul>

This whole task would be easy if we were pulling from a single static category or author—the query_posts function offers simple parameters. But pulling that information dynamically is slightly trickier.

All we need is work out which category/author the post is in and use that data to get the information. 5 posts are grabbed - then, when looping through the posts, we double check to make sure that the current post is not being linked to redundantly.

Because of the layout of the theme, we need to do all of this before the post is displayed. At the time I found the easiest method was to save the current page’s data as a new variable ($tempQuery = $wp_query;), do all the work, and then reassign the values so that the page can be updated as normal.

No matter how you code it, supporting your posts with related content is valuable to readers who want additional context and to bloggers who want a stickier site.


Related articles:

Your choice for site templates and wordpress themes

Comments

Got something to say?

You must be logged in to post a comment.