2

How can I make a similar posts section in my theme, but without using a plugin. I'm going to be giving my theme away for free, so I don't want to have to force people to install plugins to use my theme.

How can it be done?

1

Put this in your single.php:


$tags = wp_get_post_tags($post->ID);
if ($tags) {
$first_tag = $tags[0]->term_id;
$args=array(
'tag__in' => array($first_tag),
'post__not_in' => array($post->ID),
'showposts'=>4,
'caller_get_posts'=>1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); 
 // post content stuff here
endwhile;
wp_reset_query();
}
}

3

The line between theme code and plugin code is more about intended purpose than technical limitation. Either can do what other does.

If you want something simple (posts with same tag or around that) it won't be an issue to include it directly in functions.php.

But full-featured related posts solutions can get complex fast, which means they are slow, which means they need intelligent caching... To get something like that best way would be to adapt some plugin, bundle with theme and make use of it.

  • I'll only be displaying the similar posts title and the title will be a link, so I don't think it would be too difficult or complex. I don't need all the features the plugins have, just to display like 2 or 3 similar posts on the homepage and in the single post pages. – Jared Jan 14 '11 at 18:07
2

Decide what you want to consider a "similar post". The simplest approach is to pick out posts that have one or more tags in common with the current post. This should do that (within your loop):

$tags_in = array_map( 
    create_function('$tag','return $tag->term-id;'), 
    get_the_tags() );
$similar_posts = get_posts( array(
    'tag__in' => $tags_in ) );

Of course, there are much more sophisticated ways to find related posts, mostly involving comparison of post titles, and word analysis of content. Look at the code from Yet Another Related Posts plugin or any other examples, before you go too deep on your own.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.