Related posts plugin for WordPress
I have been dissatisfied with the existing related entry plugins for WordPress, so, in typical hacker fashion, I wrote my own.The other relatedness plugins I’ve seen work by pattern matching against the title or excerpt of the current article, using something like MySQL’s
MATCH AGAINST operator. While this may be acceptable for many people, it didn’t work for me; I figured keywords would be the most effective way of determining entry relatedness. Since I was already adding keyword to my posts, and spending a bit of time thinking about them, determining relatedness using these keywords made a lot of sense to me.
The plugin fetches articles based on keyword overlaps, and displays them as an unordered list. Posts with more keyword matches to the current post are displayed first (i.e., they are more relevant). For example, if the current post has keywords foo, bar, and baz, then a post with keywords foo and bar will be more related than a post with keywords bar. If there are multiple posts with the same keywords, they are displayed with the most recent first. To keep this from degenerating into madness and thrashing the database, only a limited number of related articles (5) are fetched by default. My test dataset had about 100 posts, and many of them have 10+ keywords; before I added the limiting criteria, posts with a lot of keywords were running hundreds of SQL queries. But I was getting excellent results. :)
To apply keywords to your post, create a custom field named
keywords, and apply each keyword to it (as a separate value):
Usage is simple:
<?php dlc_related(); ?>
This will emit:
<h2 class="related">Related Posts</h2> <ul class="related"> <li class="related">...</li> </ul>
As you can see, the
<li> all have a CSS
class of “related”, so that they can be styled. Future versions of the plugin will have a function to simply return the related posts, and a version that takes formatting parameters like all the other WordPress tags.
dlc_related takes two optional parameters: The first is the number of related posts display (defaults to 5) and the second is the name of the custom field to use (defaults to
keywords). You can use different values for these:
<?php dlc_related(10, "tags"); ?>
I welcome feedback, patches, feature requests, etc about the plugin.