Related Posts with WordPress

without Plugin and the help of Custom Fields

2011

While looking around for a code to show Similar Posts I found this great piece of code. The problem is, that it always takes the first tag — which are sorted alphabetically. So I extended the code to chose the tag you like manually by a value in the custom fields. If you leave it blank it will still take the first tag.
You have to put the code in the file single.php in your theme. The code has to be in the loop.

You have to name the Custom Field tagnumber or you have to change it in the code. If you for example fill in the value 2 it will be the 3 tag since the array starts to count with 0. If you like you can add a +1 in the code.

Have fun. Here is the code:

<?php

   $tags = wp_get_post_tags($post->ID);

   if ($tags) {
     $tagnumber = get_post_custom_values("tagnumber"); // Get the value/tagnumber from Custom field
     if (isset($tagnumber[0])) {
       $tagnumber = get_post_meta($post->ID, 'tagnumber', true); // If there is a value take it...
     }
     else {
       $tagnumber = 0; // ...otherwise take the first tag
     }                        

   $first_tag = $tags[$tagnumber]->term_id;
   $args=array(
    'tag__in' => array($first_tag),
    'post__not_in' => array($post->ID),
    'showposts'=>4, // Number of related posts
    'caller_get_posts'=>1
   );
   $my_query = new WP_Query($args);

   if( $my_query->have_posts() ) {
     echo 'Related Posts';
     while ($my_query->have_posts()) : $my_query->the_post(); ?>
     <a href="<?php the_permalink() ?>" rel="bookmark" title="Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a>

 <?php
 endwhile;
 }
 }
?>