It’s not easy to keep your readers on your website. It’s a challenge to provide new readers valid information, even though they were written a while ago but still up to date. A good idea is to provide posts from the same category as the post, the reader is reading currently. You can create a little function, which is listing related posts based on the category ID.
The following little function, can be used as Plugin or in functions.php
of your theme. It displays posts depending of the category. This function has three parameters:
$limit
(int) amount of posts to display$catName
(bool) echo category name,TRUE
orFALSE
$title
(string) String for a text before all entries
/**
* related post with category
* @param: int $limit limit of posts
* @param: bool $catName echo category name
* @param: string $title string before all entries
* Example: echo fb_cat_related_posts();
*/
if ( !function_exists('fb_get_cat_related_posts') ) {
function fb_get_cat_related_posts( $limit = 5, $catName = TRUE, $title = 'Recent Pages
' ) {
if ( !is_single() )
return;
$limit = (int) $limit;
$output = '';
$output .= $title;
$category = get_the_category();
$category = (int) $category[0]->cat_ID;
if ( $catName )
$output .= __( 'Kategorie: ' ) . get_cat_name($category) . ' ';
$output .= '
- ';
$args = array(
'numberposts' => $limit,
'category' => $category,
);
$recentposts = get_posts( $args );
foreach($recentposts as $post) {
setup_postdata($post);
$output .= '
- ' . get_the_title($post->ID) . ' '; } $output .= '
This is just a basic function and you can expand it of course. Also you could integrate some queries, for example, if there are no articles, it won’t display a title. In this example it will also display posts from subcategories.
Enjoy! And maybe some of you have a nice idea to implement more features in this function and let us know about it in our comment area.
Comments
9 responses to “Related Posts on Category”
great, I just love your blog – very good WordPress tutorials!
Thank you Dainis, and I’m an avid reader of your blog, great content. 🙂
Alex – thanks then you will be also very glad to see new upcoming article showcasing wordpress 2.8. tutorials.. and many of them definitely come from your site 🙂
oh, that is awesome Dainis, looking forward to see it. Thanks a lot for the recognition!
Great function. You could also add a category icon (an icon assigned to a category) thank to the Category Icons plugin that you can download at http://www.category-icons.com. All you have to do is to add:
get_cat_icon("cat=".$category)
in the if ( $catName ) block, just before __( ‘Kategorie: ‘ ).
this also displays the current post, you should avoid that
after add this code to functions, how I will use related post in the single.php?
…?
Is it possible to add an image from each of the posts (such as the first image) in the form of a thumbnail?
great post, you should think of creating a plugin so that more people could use and recognize your job. Thanks for sharing