Tom-Hayes
1/19/2017 - 7:08 PM

Drop this snippet into your functions.php file located in your theme folder. It works by showing posts that have the same tag as the curren

Drop this snippet into your functions.php file located in your theme folder. It works by showing posts that have the same tag as the current post you're viewing. To display the related posts on your post page you need to locate your single post template (often single.php) and then enter the following snippet: where you would like the related posts to show.

function related_posts() {
  global $post;
  $tags = wp_get_post_tags( $post->ID );
  if($tags) {
    foreach( $tags as $tag ) {
      $tag_arr .= $tag->slug . ',';
    }
    $args = array(
      'tag' => $tag_arr,
      'numberposts' => 3, // Set the amount of posts you wish to display
      'post__not_in' => array($post->ID)
    );
    $related_posts = get_posts( $args );
    if($related_posts) {
      echo '<h4>Related Posts</h4>';
      echo '<ul class="related-posts">';
      foreach ( $related_posts as $post ) : setup_postdata( $post ); ?>
        <li class="related_post">
          <a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>">
            <?php the_title(); ?>
          </a>
        </li>
      <?php endforeach;
      </ul>
      <?php  wp_reset_postdata(); ?>
    }
  }
}