Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to show related posts in WordPress without using plugin

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 442
    Comment on it

    Hi,

    As we see in most of the WordPress websites that each single blog post is having related postsat the end of the content. It is the technique to engage the visitor in the website by giving them suggestions for reading another alike blog posts. This helps our website for staying visitors in website for most of the time.

    This can be done by most of the plugins as there are many plugins for that in wordpress.org website. But we can do this in any of the wordpress blog website by just writing few lines of code in wordpress' theme file.

    As many plugins make the website heavy to load and also sends too much request to serverby which sometimes server break so its good to use few lines of code.

    Just copy the code below and paste in worpress theme's single.php file in the place where you want to display related posts.

    <?php  //list posts
    
      $backup = $post;  // backup the current object
    
      $tags = wp_get_post_tags($post->ID);
    
      $tagIDs = array();
    
      if ($tags) {
    
        $tagcount = count($tags);
    
        for ($i = 0; $i < $tagcount; $i++) {
    
          $tagIDs[$i] = $tags[$i]->term_id;
    
        }
    
        $args=array(
    
          'tag__in' => $tagIDs,
    
          'post__not_in' => array($post->ID),
    
          'showposts'=>5,
    
          'caller_get_posts'=>1
    
        );
    
        $my_query = new WP_Query($args);
    
        if( $my_query->have_posts() ) {
    
          while ($my_query->have_posts()) : $my_query->the_post(); ?>
    
            <h3><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php      the_title();          ?>"><?php the_title(); ?></a></h3> // title and links of related posts
    
          <?php endwhile;
    
        } else { ?>
    
          <h2>No related posts found!</h2>
    
        <?php }
    
      }
    
      $post = $backup;  // copy it back
    
      wp_reset_query(); // to use the original query again
    
    ?>

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: