Adding ‘Related Posts’ to WordPress articles and 404 error pages

Many blogs have a list of related articles after each of their posts. I wanted something similar for my WordPress blog but found it wasn’t as easy to do as I thought it would be.

At the same time I was interested in capturing any access attempts to non-existent pages (causing a 404 error), and showing a list of suggested links. This is something that is useful to do to turn people who get 404 errors into readers of your blog.

I first looked at the WASABI related post plugin. It did what I wanted with the related entries but it requires you to add a tag to each post where you want the related entries to appear. There is also a version of the plugin which can generate sensible links for any 404 errors. It does this by turning the incorrect URL into a list of terms which are then used to find related posts.

The next plugin that I read about was called ‘Aizattos Related Posts’. This plugin was originally based on WASABI but has evolved since. It inserts related links without needed to add any special tags to the posts. A lot of good feedback was given about this plugin but it seems that the author has removed it from the original download site. Fortunately someone has re-posted this plugin to this site.

I therefore have what I need in two separate plugins. I installed the Aizattos Related Posts plugins and then created a modified version of the WASABI 404 handling code. The 404 handler is in one function ‘related_posts_404’. Below is the modified version of the WASABI code which will work with the Aizattos Related Posts plugin. As well as showing the related links it also shows an extract from the post page. Just put this function in the Aizattos Related Posts plugin PHP file.

related_posts_404()
function related_posts_404($limit=5, $len=50,
	$before_title = '', $after_title = '',
	$before_post = '', $after_post = '',
	$show_pass_post = false, $show_excerpt = true) {
    global $wpdb, $post;
    $before_title   = '<span class="aizatto_related_posts_title" >';
    $after_title    = '</span>';
    $before_excerpt = '<div class="aizatto_related_posts_excerpt">';
    $after_excerpt  = '</div><p></p>';
    $before_related = '<li>';
    $after_related  = '</li>';
    $search_term = $_SERVER['REQUEST_URI'];
    $search = array ('@[/]+@', '@(..*)@', '@[-]+@', '@[_]+@', '@[s]+@', '@archives@','@(?.*)@','/d/');
    $replace = array (' ', '', ' ', ' ', ' ', '', '','');
    $search_term = preg_replace($search, $replace, $search_term);
    $search_term = trim($search_term);
    $terms = $search_term;
    $time_difference = get_settings('gmt_offset');
    $now = gmdate("Y-m-d H:i:s",(time()+($time_difference*3600)));
    // Primary SQL query
    $sql = "SELECT ID, post_title, post_content,"
         . "MATCH (post_name, post_content) "
         . "AGAINST ('$terms') AS score "
         . "FROM $wpdb->posts WHERE "
         . "MATCH (post_name, post_content) "
         . "AGAINST ('$terms') "
		 . "AND post_date <= '$now' "
         . "AND (post_status IN ( 'publish',  'static' ) && ID != '$post->ID') ";
    if ($show_pass_post=='false') { $sql .= "AND post_password ='' "; }
    $sql .= "ORDER BY score DESC LIMIT $limit";
    $results = $wpdb->get_results($sql);
    $output = '';
    if ($results) {
        foreach ($results as $result) {
            $title = stripslashes(apply_filters('the_title', $result->post_title));
            $permalink = get_permalink($result->ID);
            $output .= $before_title
                .'<a href="'. $permalink .'" rel="bookmark" title="Permanent Link: '
		. $title . '">'
		. $title . '</a>'
		. $after_title;
            if ($show_excerpt=='true') {
                $post_content = strip_tags($result->post_content);
                $post_content = stripslashes($post_content);
                $words=split(" ",$post_content);
                $post_strip = join(" ", array_slice($words,0,$len));
                $output .= $before_excerpt . $post_strip . $after_excerpt;
                }
        }
        echo $output;
    } else {
        echo $before_title.'Fuzzy ...'.$after_title;
    }
}

Although no code modifications are needed for the related links in your normal posts, you will have to make a modification to your theme’s 404 page if you want related links for any ‘Not Found’ errors. In blue below is the modification I made to my 404.php for the default theme.

blog/wp-content/themes/default/404.php
<?php get_header(); ?>
	<div id="content" class="narrowcolumn">
		<h2 class="center">Error 404 - Not Found</h2>
		<p>We're sorry but the page you are looking
		for isn't at this location. Were you perhaps
		looking for one of these articles?</p>
		<?php related_posts_404(); ?>
	</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>



Tags: , , , , ,

Leave a Reply

Do NOT fill this !