Jun 12th
2010

WordPress How To: Add Related Posts Section Without Plugin


While reading famous blogs like Nettuts, Tuttoaster… you will be very impressive about the related posts section which appeared immediately after the blog post content. In this article, I will show you how to add it to your WordPress theme without any additional plugin and very easy to do.

What are we going to do?

First, lets look about what we will do, this is a screenshot taken in my localhost website:

I want to build a related posts section that can automatically get related posts based on the current post tag, furthermore, it can automatically displays the thumbnail for each related post item by looking for the first image in each related post.

… and how you can archive it

To archive it, I need using additional Php image-resize script to resize the post thumbnail to a fixed size, and it’s TimThumb, so in the first step, you need to download TimThumb script and then upload it to your WordPress theme folder.

The second step, add this code to your functions.php file (in your theme folder, if your theme doesn’t has it, let’s create one):

function catch_that_image() {
  global $post, $posts;
  $first_img = '';
  ob_start();
  ob_end_clean();
  $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
  $first_img = $matches [1] [0];

  if(empty($first_img)){ //Defines a default image
    $first_img = "/images/default.jpg";
  }
  return $first_img;
}

The third step, you add this code to your single.php file (It must be pasted within the loop):

		<!-- Display related posts without a plugin -->
			<?php
			$tags = wp_get_post_tags($post->ID);
			if ($tags) {
			  echo '<aside id="related-post"><h3>Related Posts</h3><ul>';
			  $first_tag = $tags[0]->term_id;
			  $args=array(
				'tag__in' => array($first_tag),
				'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(); ?>
				  <li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>">
					<img src="<?php bloginfo('template_directory'); ?>/timthumb.php?src=<?php echo catch_that_image() ?>&w=100&h=100&zc=1" />
					<?php the_title(); ?>
				  </a></li>
			<?php endwhile; }
				echo '</ul></aside><br class="clear" />';
				wp_reset_query();
			}?>
		<!-- End of display related posts without a plugin -->

Notes:

  • In the code above, I added “<aside id="related-post">” because my theme was built on Html5 syntax, if your theme doesn’t use Html5, please replace it with the “<div>” syntax.
  • If you like another size of post thumbnail, please edit this line “&w=100&h=100“, replace “100” with the size you need.
  • TimThumb script can only process the local image, so be sure that the first image in your related posts must be hosted in your domain host.

And the final step, CSS!
Here is my Css styling, you can change it to whatever you want:

#related-post h3 {font-size:1.6em;margin:5px 0}
#related-post ul {list-style:none;}
#related-post ul li{float:left;margin-right:15px;width:110px}
#related-post img {border:1px solid #ddd;background:#F9F9F9;padding:5px}
#related-post a:hover {color:#c00}

Conclusion

Of course, there’re many ways to add related posts section to your theme available on the Internet, you can follow any of them but I like the way I show you because it’s very simple, easy to do and can automatically process the post thumbnail images for you, if you have another better idea, please let’s me know :)

The Blogging Profit Supremacy

Have you ever been dissatisfied with your income? Don't waste your time any more, take the lessons I've learned in 3 years and start making your money online the right way now!

Put your information below to DOWNLOAD this special report For $21 FREE! 
(Currently being sold on Amazon - Limited offer only for IntenseBlog's readers)
 



Powered by WPSubscribers

About Jenni R

Jenni is a banker who love to work with PHP coding, Wordpress blog and Web design... She currently is a Chief Branding Officer of Intense Blog. In this year, Jenni has built an awesome Wordpress plugin called as: WPSubscribers, which will help you build the mailing list instantly and was sold more than 1000 copies, let's check it out!

Connect with Jenni on Google, Facebook and Twitter.

Comments

  1. camikat says:

    Thanks, very nice and useful post…
    camikat last post: Ressources et tutoriaux pour mieux comprendre Joomla

  2. I’m sorry but code line 6 for functions.php makes my whole site crash. Running WP 3.0RC1.

    • Jennifer R says:

      I’m sorry to heard about that, this code has not tested in WordPress 3.0, but WP 3.0 is NOT official released :), it works well in WP version up to 2.9.2

  3. But it’s a really good idea and WP 3.0 is just around the corner. Can you please make it compatible with 3.0? I’d rather not use a plugin for this functionality.

  4. I just trashed my WP 3.0 RC1 installation by trying to upgrade it to RC3. At this point I think we can safely say that the error is on my side :)

  5. TechGopal says:

    really useful trick
    i use jr related post plug in
    bt now after reading this post i will try this trick…..

  6. Jake says:

    HI I am Using IGIT wordpress Related posts with thub image which is very nice.

  7. Namila says:

    very usefull post.thankyou for sharing this info…..

  8. Mike says:

    Very nice, I’ll try this on my next WP site. Thanks!

  9. Nope, it still crashes out:
    Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in /home/web26168/domains/domain.se/public_html/wp-content/themes/starmagazine/functions.php on line 227
    Gunnar Lindberg Årneby last post: Datormöbel i dansk design

  10. Carkod says:

    I do not know if you are a foreign English speaker but you are making lots of spelling mistakes and you seem unaware. I should say that a person that writes many articles (more than that, you are a chief editor!) must revise her spelling and write things as correctly as possible for fully understanding. One of the words that I suppose you are writing it wrong all the time is “archive” (a noun), which is not the same as “achieve” (a verb). Also, beware with 3rd person, e.g. “if your theme doesn’t HAVE one”, “I’m a banker who LOVES to work…”. Hope this helps.

    • Jennifer R says:

      Thanks for your advice, I’m not a foreign English speaker, I’ve just moved to U.S from Japan, and I still in leaning English process but I think a language couldn’t block my love for blog :) .I’m very happy if you could help me to fix these errors.
      Once again, thanks you so much.

    • Wayne Hatter says:

      Carkod, Chill out! Just figure it out what she is trying to say. There is no need to correct her in open like this. It is very nonprofessional.
      Wayne Hatter last post: Jody Finds The Solution for Managing Multiple WordPress Blogs

    • theReal says:

      Okay, since you’re such a grammar Nazi, let’s fix your grammar while we’re at it, shall we, as you “seem unaware.”

      Lack of comma: “you are a foreign English speaker but you are making lots of spelling mistakes” > ‘you are a foreign English speaker, but you are making lots of spelling mistakes’

      Incorrect grammar: “I should say that a person that writes” > ‘In my opinion, a person that writes’

      Incorrect grammar: “correctly as possible for fully understanding” > ‘as correct as possible for full understanding’

      Incorrect grammar: “of the words that I suppose you are writing it wrong all the time” > ‘of the words I notice you often spell incorrectly’

      People in glass houses shouldn’t throw stones, buddy.

      @Jennifer, thanks for the post. Good stuff.

  11. kevin says:

    Hi

    Am I right in guessing that this method will be a lot less of a drain on server resources than most of the plugins? One of my sites is a pretty big site and I have tried adding related articles plugins but they have killed my cpu time allowance.
    If the trick is just pulling sites from tags then it should be a lot more efficient – but I’m just guessing at that.

    Kevin

    • Jennifer R says:

      Hi Kevin, I think you’re right, because other WP plugins calculate related articles aren’t only based on post tags but also post’s category, keyword and/or title.

  12. Отличная статейка. Добавлю я вас и избранное наверно..))

  13. Ridhuan says:

    Love you so much.. I’ve been looking on how to automatically use the post’s first image as thumbnail and here it is in a few lines of your codes. I’m designing my first WP theme and WP >= 2.9 have the featured image function but they are not automatic. I might also add this Related Posts to my theme. Thank you very much. Haven’t test it yet but sure it will work nicely. Update you later.
    Ridhuan last post: WordPress Automatic Facebook Page Update

  14. Ridhuan says:

    Problem with your line 6 but I replaced it with this:

    $output = preg_match_all(‘//i’, $post->post_content, $matches);

    and now it works fine. And in line 9 you typed “empty” twice.

  15. Ridhuan says:

    Problem with your line 6 but I replaced it with this:
    $output = preg_match_all(‘/<img.+src=[\'"]([^\'"]+)[\'"].*>/i’, $post->post_content, $matches);
    and now it works fine. And in line 9 you typed “empty” twice.

  16. vookas.com says:

    how can i use my site this?
    vookas.com last post: Megan Fox American popular hot model and Actress photos

  17. Live Cricket says:

    worked perfectly on my blog. Thanks a lot!!!

  18. Jami Gibbs says:

    Thanks very much for posting this!

    I wanted to share my modification of your code. I removed the ‘catch_that_image’ function and replaced it with the ‘Featured Image’ feature that’s used in WordPress 3.0+.

    https://gist.github.com/1113929

    Cheers!

  19. Chris from GoDaddy Coupons says:

    I savor, lead to I found just what I was looking for. You’ve ended my four day lengthy hunt! God Bless you man. Have a great day.

  20. It is good to show related post in wordpress blog without plugiN. iIt will consume less bandwidth and time to load. Thanks for your suggestion.

  21. Struat from Adobe Certification says:

    Hmm nice way to make related posts. Very important information specially for bloggers and developers.

  22. mohammad says:

    really good post man!
    go ahead ;)

  23. mohammad says:

    awesome post brother
    its usefull for my wordpress blog.
    thnaks
    mohammad last post: Top 10 Earning ‘Websites’ Of 2011

  24. Yvane from Access Remote says:

    Thanks for sharing the post it’s brilliant!

  25. thanks for that article i want related post in our blog without using plugin….can u please tell me what plugin are using for popular post?

  26. john says:

    Very interesting post and also very easy to understand thanks for sharing cool trick

  27. Hi, Your code works like a charm.. I have implemented this method on my Football Galleries blog. I prefer using timthub script instead of using featured image method (which is suggested by jami) because by using timthumb image automatically appear as thumbnail without clicking in featured wp 2.9 panel post.
    Million thanks for ya..!!
    football galleries last post: Gareth Bale Slide Tackle Photo

  28. Sana says:

    Amazing sharing of wordpress plugins..
    Sana last post: MEHNDI DECOR

Speak Your Mind

*

CommentLuv badge
Please leave these two fields as-is:

This site uses KeywordLuv. Enter YourName@YourKeywords in the Name field to take advantage.