Related Posts function in WordPress

Related post is a very useful function which can keep the visitors surfing on your website based on the post tags.

You can install plugins to do this, or you can simply add the following codes in the single.php

<div id="related_posts">
        //list 5 post titles related to the tags on current post
        $tags = wp_get_post_tags($post->ID);
        if ($tags) {
            echo '<h1>Related Posts</h1>';
            //read the current tags in an array
            $current_tags = array();
            foreach ($tags as $tag){
                $current_tags[] = $tag->term_id;
                'tag__in' => $current_tags,
                'post__not_in' => array($post->ID),
            $my_query = new WP_Query($args);
            echo '<ul>';
            if( $my_query->have_posts() ) {
                while ($my_query->have_posts()) : $my_query->the_post(); 
                    <li><span class='related_post_date'><?php the_time('M jS, Y');?></span>: <a href="<?php the_permalink() ?>" rel="bookmark" target="_blank" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>

            echo '</ul>';

Leave a Reply

Your email address will not be published. Required fields are marked *