Similar Posts – NO plugin

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?

Related posts

Leave a Reply

3 comments

  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();
    }
    }
    
  2. 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.

  3. 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.