Snippet · Mecha CMS

Code snippet collection for developers.

Basic Related Posts

Author: Taufik Nurrohman · 396 Views

Tweet

Show list of pages in random order, filtered by the similarities of the current page file name.

<?php

$_path = PAGE . DS . Path::D($url->path);
$_chunk = 7;
$_relates = [];

echo '<h3>Related Posts</h3>';
if ($_current = Lot::get('page')) {
    if ($_pages = Get::pages($_path, 'page')) {
        $_slug = $_current->slug;
        $_query = explode('-', $_slug);
        foreach ($_pages as $_page) {
            $_n = Path::N($_page['path']);
            if ($_n === $_slug) continue; // Is the same page, skip…
            foreach ($_query as $_v) {
                if (strpos($_n, $_v) !== false) {
                    $_relates[] = $_page['path'];
                }
            }
        }
    }
    $_relates = array_unique($_relates); // Remove duplicate(s)…
    if (!empty($_relates)) {
        echo '<ul>';
        foreach (Anemon::eat($_relates)->shake()->chunk($_chunk, 0) as $_relate) {
            $_relate = new Page($_relate);
            echo '<li>' . HTML::a($_relate->title, $_relate->url) . '</li>';
        }
        echo '</ul>';
    } else {
        echo '<p>This post has no relations with other posts.</p>';
    }
}

?>
  • $_path → Automatic folder selection based on the current page path.
  • $_chunk → How many pages you want to list.

0 Comments

No comments yet.