Random related posts by tag/taxonomy

Hi, I wondered how to best integrate random related posts by tag/taxonomy overlap. In the “solutions” section of the docs, this is done manually. I’m also aware how to grab random content

$randomarticles = $pages->find('blog')->children()->shuffle()->limit(3);

and then a foreach loop. But how do I best check all articles for overlapping tags since articles might have more than 1 same tag?

Maybe the Related Posts plugin is a starting point: http://getkirby-plugins.com/relatedpages

Edit: Come to think about it, it’s not even necessary to use a plugin. A filter with a callback based on the current tags should do, something like:

$tags = $page->tags()->split(',');
$children = page('blog')->children()->visible();
$relatedPages = $children->filter(function($child) use($tags) {
  return in_array($child->tags()->split(','), $tags);
})->shuffle()->limit(3);

Thanks! Just gave it a try getting a parse error… Unexpected T_string in the $relatedPages line :confused:
At first glance it looked as if a { was missing before the use but somehow I cannot find what’s missing.

Ok, then try this:

$tags = $page->tags()->split(',');
$children = page('blog')->children()->visible();
$relatedPages = $children->filter(function($child) use($tags) {
          if (array_intersect($child->tags()->split(','), $tags)) {
            return $child;
          }
       });
foreach($relatedPages->not($page) as $related) {
  echo $related->title();
}
1 Like

Thanks, that did the job for me! For completeness sake, here the code that I use including the shuffle and limit;

<?php
$tags = $page->tags()->split(',');
$children = page('blog')->children()->visible();
$relatedPages = $children->filter(function($child) use($tags) {
          if (array_intersect($child->tags()->split(','), $tags)) {
            return $child;
          }
       });
?>
<ul>
<?php foreach($relatedPages->not($page)->shuffle()->limit(3) as $related): ?>
  <li><a href='<?php echo $related->url(); ?>'><?php echo $related->title(); ?></a></li>
<?php endforeach ?>
</ul>
2 Likes