News Manager blog

Similar/related posts in News Manager

The other day morvy posted an interesting piece of code for News Manager, that displays a list of similar/related posts (having tags in common):


$num_post = 5;
$slugs = array();
$url = nm_get_url('post');
$posts = nm_get_tags();
foreach($posts as $tag => $post) {
    if(nm_post_has_tag($tag)) {
        foreach ($post as $slug) {
            $slugs[] = (string)$slug;
        }
    }
}
$slugs = array_unique($slugs);
if(($key = array_search(nm_post_slug(false), $slugs)) !== false) {
    unset($slugs[$key]);
}
shuffle($slugs);
$slugs = array_slice($slugs, 0, $num_post);
$all = nm_get_posts();

echo '<ul class="nm_similar_post">';
foreach ($all as $post) {
    if(in_array($post->slug, $slugs)) {
        echo '<li><a href="'.$url.$post->slug.'" title="'.$post->title.'">'.$post->title.'</a></li>', PHP_EOL;
    }
}
echo '</ul>';

(http://get-simple.info/forums/showthread.php?tid=4339&pid=50761#pid50761)

A possible way to use it could be:

  • paste the code into a new component, named e.g. nm-similar-posts
  • enable Custom Settings and enter this below:
single componentBottomPost nm-similar-posts

Another way could be:

  • paste the code into a new component, named e.g. nm-similar-posts
  • insert this code somewhere in your template file -- you will probably need it after <?php get_page_content(); ?> :
<?php if (nm_is_single()) { get_component('nm-similar-posts'); } ?>

« Back to News Manager blog

blog comments powered by Disqus