Implementing a Related Posts Or Articles Section On Your Website Using Tags

Implementing a Related Posts Or Articles Section On Your Website Using Tags Posted August 5, 2009 @ 8:44pm by Phil

A great way to keep traffic on your website is to offer related content on your pages. For me, this means linking my posts to other related posts. The simplest way to do this would be to go through all my posts and link to my other posts which I choose to be related. This would not be the easiest way though. Being a lazy programmer, I want the easiest solution that will require the least amount of work.

So let me think about this some more. In order to be related, posts should share at least one common topic. Since I already identify the topic using tags, I can probably use them to infer related posts. So I guess the posts that share the greatest number of tags are the most related.

Surprisingly, this is even easier to implement. Using the above idea, I was able to generate the following SQL statement that will generate the list of posts that share the greatest amount of tags:

SELECT    post_id,
      COUNT(post_id) AS count
FROM    post_tags
WHERE    post_id != 'post_id'
AND      tag_id IN (
  SELECT    tag_id
  FROM    post_tags
  WHERE    post_id='post_id'
)
GROUP BY  post_id
ORDER BY  count DESC

Download Source: related_posts.sql

That's all there is. Now we have a list of related posts ordered by relevance.

What if I don't tag my content?

If you don't tag your content, there are services out there that will take your text and generate related tags (much like Google does to provide related ads in Adsense). When I first started this site, I tried something like that but the tags generated were terrible. Probably something to do with the fact that I don't saturate my articles with key words. So you could try one of those services or just start tagging your content, which you should probably get in the habit of doing it anyway for SEO.

Tags: PHP/MySQL, Webmasters Tips