惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

G
Google Developers Blog
Apple Machine Learning Research
Apple Machine Learning Research
小众软件
小众软件
Recent Announcements
Recent Announcements
阮一峰的网络日志
阮一峰的网络日志
IT之家
IT之家
A
About on SuperTechFans
量子位
Engineering at Meta
Engineering at Meta
B
Blog
The Cloudflare Blog
博客园 - 【当耐特】
Hugging Face - Blog
Hugging Face - Blog
Y
Y Combinator Blog
J
Java Code Geeks
D
DataBreaches.Net
aimingoo的专栏
aimingoo的专栏
T
Tailwind CSS Blog
H
Help Net Security
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
V
V2EX
Stack Overflow Blog
Stack Overflow Blog
C
Check Point Blog
酷 壳 – CoolShell
酷 壳 – CoolShell

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Dynamic related articles in PHP without a database
Odilon HUGON · 2026-05-10 · via DEV Community

Odilon HUGONNOT

The "related articles" section at the bottom of a blog post is exactly the kind of thing you hardcode at first — two links picked by hand — and then forget to maintain. The result: stale suggestions pointing to unrelated articles, or worse, articles that no longer exist.

On this blog, all content is described in a single posts.json file, with each article's slug, category, and tags. That's enough to automatically calculate relevant suggestions without a database.

The problem with hardcoded links

The initial version passed an array of links to blog_footer():

<?php blog_footer([
    ['url' => '/blog/commentaires-sans-bdd-php', 'title' => 'Adding comments...'],
    ['url' => '/blog/creer-un-blog-avec-claude-code', 'title' => 'Building a blog...'],
]); ?>

Enter fullscreen mode Exit fullscreen mode

Functional, but requires manual maintenance in every article file. With 10 articles it's manageable, with 50 it becomes unworkable — and it never automatically improves when you publish a new article that would be more relevant.

The source of truth: posts.json

Each article is described in posts.json with its metadata:

{
  "slug": "analytics-php-sans-cookies-rgpd",
  "title": "Analytics PHP sans cookies ni base de données",
  "date": "2026-02-25",
  "category": "Retour d'expérience",
  "tags": ["php", "analytics", "rgpd", "sécurité", "no-database"]
}

Enter fullscreen mode Exit fullscreen mode

This is already used for the blog listing and the sitemap. Might as well use it for suggestions too.

The scoring algorithm

The principle is straightforward: for each candidate article (all articles except the current one), we calculate a relevance score based on two criteria:

  • +2 per shared tag — tags are the most precise signal
  • +1 if same category — a broader contextual signal

We sort by descending score, break ties by most recent, and keep the top 3. Articles with a score of 0 (nothing in common) are excluded.

function find_related_posts(string $slug, int $limit = 3): array {
    $all = json_decode(file_get_contents(__DIR__ . '/posts.json'), true) ?? [];

    // Find the current article
    $current = null;
    foreach ($all as $p) {
        if ($p['slug'] === $slug) { $current = $p; break; }
    }
    if (!$current) return [];

    $current_tags = $current['tags'] ?? [];
    $current_cat  = $current['category'] ?? '';

    // Score the candidates
    $scored = [];
    foreach ($all as $p) {
        if ($p['slug'] === $slug) continue;

        $score = count(array_intersect($current_tags, $p['tags'] ?? [])) * 2
               + ($p['category'] === $current_cat ? 1 : 0);

        if ($score > 0) {
            $scored[] = ['score' => $score, 'post' => $p];
        }
    }

    // Sort by score desc, then date desc on ties
    usort($scored, fn($a, $b) =>
        $b['score'] <=> $a['score'] ?: strcmp($b['post']['date'], $a['post']['date'])
    );

    return array_map(fn($s) => [
        'url'   => '/blog/' . $s['post']['slug'],
        'title' => $s['post']['title'],
    ], array_slice($scored, 0, $limit));
}

Enter fullscreen mode Exit fullscreen mode

Integration in blog_footer()

blog_footer() already accepted a $slug parameter (used to load comments). It just needs to auto-trigger the calculation when no explicit list is passed:

function blog_footer($related_posts = [], $slug = null) {
    if (empty($related_posts) && $slug !== null) {
        $related_posts = find_related_posts($slug);
    }
    // ...
}

Enter fullscreen mode Exit fullscreen mode

On the article side, the call becomes:

<?php blog_footer([], 'my-article-slug'); ?>

Enter fullscreen mode Exit fullscreen mode

That's it. Existing articles that were already passing their slug didn't need to be modified — they inherit the automatic behavior.

Why weight tags x2

A category groups articles with similar context but not necessarily similar subjects — "Lessons learned" can cover PHP just as well as Bash. Tags are more precise: two articles sharing the tags php and no-database are probably discussing the same problem. The x2 weighting on tags ensures that topical proximity takes precedence over categorical proximity.

Limitations

The posts.json file is read on every article page load. On a low-traffic blog with a dozen articles, this is negligible. If volume grows, a simple opcache or file cache would be sufficient — but that's not today's problem.

The algorithm doesn't consider the actual content of the articles, only their metadata. The quality of suggestions therefore depends directly on the quality of the tagging. Which is a good reason to be deliberate with tags rather than slapping them on at random.