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

推荐订阅源

GbyAI
GbyAI
N
News and Events Feed by Topic
D
DataBreaches.Net
MongoDB | Blog
MongoDB | Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Engineering at Meta
Engineering at Meta
T
Tailwind CSS Blog
博客园_首页
Microsoft Azure Blog
Microsoft Azure Blog
Y
Y Combinator Blog
博客园 - Franky
Hugging Face - Blog
Hugging Face - Blog
月光博客
月光博客
A
About on SuperTechFans
I
InfoQ
S
Securelist
Last Week in AI
Last Week in AI
S
Schneier on Security
C
CXSECURITY Database RSS Feed - CXSecurity.com
Hacker News: Ask HN
Hacker News: Ask HN
Schneier on Security
Schneier on Security
Know Your Adversary
Know Your Adversary
腾讯CDC
大猫的无限游戏
大猫的无限游戏
S
Security @ Cisco Blogs
博客园 - 三生石上(FineUI控件)
Simon Willison's Weblog
Simon Willison's Weblog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
T
Tor Project blog
美团技术团队
aimingoo的专栏
aimingoo的专栏
G
Google Developers Blog
罗磊的独立博客
Vercel News
Vercel News
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
The Cloudflare Blog
S
Secure Thoughts
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Latest news
Latest news
Recent Announcements
Recent Announcements
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
L
LINUX DO - 热门话题
Security Latest
Security Latest
TaoSecurity Blog
TaoSecurity Blog
Cyberwarzone
Cyberwarzone
有赞技术团队
有赞技术团队

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Building related-post recommendations for a Shopify blog — the algorithm, not the app
Peter Hallan · 2026-05-14 · via DEV Community

Shopify gives you product recommendations out of the box. There's a whole /recommendations/products.json endpoint, a recommendations.products Liquid drop, and an entire ML pipeline behind it. For blog posts? Nothing. Zero. There is no /recommendations/articles, no recommendations.articles, no signal. If you run an editorial blog on Shopify — and a lot of stores do now, because content is how you get organic traffic without paying Meta — you're on your own.

What most themes do is one of three things:

  1. A "Latest 3 posts" widget at the bottom of every article.
  2. A hand-curated metafield where the merchant picks related posts manually.
  3. An app that you install and treat as a black box.

I've shipped all three for clients. The first one is useless. The second one only works for the first month, then nobody updates the metafields. The third one works fine but most merchants want to understand what's actually happening. So this post is about how to roll your own — the algorithm, the rendering pattern, and the things I got wrong the first two times.

I'll be upfront: I made an app for this. I'll mention it once near the end. The article isn't about the app — it's about the engineering. If you'd rather build it yourself after reading this, fantastic; that's the point.

Why "latest posts" is the wrong default

A reader who lands on your article about "summer wedding shoes for outdoor ceremonies" is interested in summer wedding shoes for outdoor ceremonies. If your latest three posts are about pet grooming, holiday gift guides, and a sustainability report, you've just shown them three exit ramps. Bounce goes up. Pages-per-session goes down. And the internal linking signal you could have given Google — "this article about wedding shoes is topically related to these other wedding shoe articles" — is wasted on noise.

The fix isn't fancy. You need a similarity function that takes the current article and returns a ranked list of other articles, where "ranked" means topically relevant, not chronologically recent. Then you render the top three or four. That's it. The hard part is doing it without slowing the page down or breaking SEO.

The baseline: tag overlap with Jaccard similarity

Every Shopify article has a tags array. Most editorial Shopify stores tag posts with things like wedding, summer, outdoor, shoes, style-guide. If two articles share a high proportion of tags, they're probably related. That's the entire premise of Jaccard similarity:

J(A, B) = |A ∩ B| / |A ∪ B|

Enter fullscreen mode Exit fullscreen mode

Intersection over union. Score between 0 and 1. Higher means more overlap. It's the simplest non-trivial similarity function you can compute, and for blog posts with reasonable tagging, it's surprisingly strong as a baseline.

You can do this in pure Liquid. No JS, no fetch, no script tag — the markup renders server-side and you get the related posts inline. Here's the loop:

{%- liquid
  assign current_tags = article.tags
  assign current_handle = article.handle
  assign scored = ''
-%}

{%- for post in blog.articles -%}
  {%- if post.handle == current_handle -%}{%- continue -%}{%- endif -%}

  {%- assign intersection = 0 -%}
  {%- assign union_set = current_tags | concat: post.tags | uniq -%}

  {%- for tag in current_tags -%}
    {%- if post.tags contains tag -%}
      {%- assign intersection = intersection | plus: 1 -%}
    {%- endif -%}
  {%- endfor -%}

  {%- assign union_size = union_set | size -%}
  {%- if union_size == 0 -%}{%- continue -%}{%- endif -%}

  {%- assign score = intersection
    | times: 1000
    | divided_by: union_size -%}

  {%- assign entry = score
    | append: '|'
    | append: post.handle -%}
  {%- assign scored = scored | append: entry | append: ',' -%}
{%- endfor -%}

{%- assign scored_list = scored
  | split: ','
  | sort
  | reverse -%}

<ul class="related-posts">
  {%- for entry in scored_list limit: 3 -%}
    {%- assign parts = entry | split: '|' -%}
    {%- assign handle = parts[1] -%}
    {%- assign related = blog.articles[handle] -%}
    {%- if related -%}
      <li>
        <a href="{{ related.url }}">
          <img src="{{ related.image | image_url: width: 400 }}"
               alt="{{ related.title | escape }}"
               loading="lazy">
          <h3>{{ related.title }}</h3>
        </a>
      </li>
    {%- endif -%}
  {%- endfor -%}
</ul>

Enter fullscreen mode Exit fullscreen mode

A few notes on this. Liquid doesn't have floats, so I multiply by 1000 before dividing to preserve precision in the sort. The string concatenation trick (score|handle,score|handle,... then split and sort) is how you get a stable sort by numeric score in pure Liquid without a sort_by filter on a dynamic key. It's ugly. It works.

The other thing: this loops over blog.articles, which on a small blog is fine. On a blog with several hundred articles you'll pay for it in render time, and blog.articles is also capped at 50 by default — you'll want to paginate or limit to the most recent N for the candidate set. In practice, scoring against the last 50 articles is more than enough for relevance; older posts are usually less relevant anyway.

Adding author as a secondary signal

Tags are noisy. Some writers under-tag, some over-tag. A second signal that's almost free: same author. If two articles share an author, that's often a strong topical signal because writers tend to specialize. Your shoe writer writes about shoes. Your sustainability writer writes about sustainability. You don't even need to look at the tags to know the next article from the same person is probably in the same orbit.

I weight this lower than tags — author is a coarse signal, tags are fine-grained — but adding +0.2 when authors match and the article is in the same blog has been a clean lift in the data I've seen. It's also the savior when tags are sparse, which on a newer blog they will be.

In Liquid:

{%- assign author_bonus = 0 -%}
{%- if post.author == article.author -%}
  {%- assign author_bonus = 200 -%}
{%- endif -%}
{%- assign final_score = score | plus: author_bonus -%}

Enter fullscreen mode Exit fullscreen mode

(Again, scaled by 1000 to play nice with integer math.)

Keyword overlap from titles and handles

The third signal is the most useful but takes the most care: content keyword overlap. Tags are author-controlled and inconsistent. The article title and the URL handle are usually clean, descriptive, and stable. "summer-wedding-shoes-outdoor" tells you a lot more than the tag summer does.

You can tokenize the title plus handle once per article, drop stopwords, and compute overlap against the current article's tokens. The bigger version of this is TF-IDF — you compute term frequency for each article and inverse document frequency across the whole corpus, then take a dot product on the resulting vectors. That's textbook IR and it works, but you don't need it for a blog with 50–500 articles. Plain keyword overlap with a stopword list gets you 80% of the win for 10% of the complexity.

I do this in JS rather than Liquid because tokenization in Liquid is painful and you can cache the token sets in localStorage or just compute them once per page load. Liquid handles the initial render with the tag-only score, then JS upgrades the list on hydration if you want a fancier score. Or — and this is what I do now — you push the whole scoring step server-side via the Section Rendering API.

Section Rendering API: why it matters

Here's the thing about doing recommendations purely in client-side JS: you lose two things you actually need.

First, SEO. Googlebot does render JS these days, but it discounts JS-rendered content and especially JS-rendered internal links. If the related-posts block is in the initial HTML, you get the full internal-link equity from day one. If it's injected on hydration, you don't.

Second, CLS. Cumulative Layout Shift is a real Core Web Vitals metric and Google ranks pages worse when they shift. A block that materializes 600ms after first paint pushes the footer down and you eat a CLS penalty. Reserving space with a skeleton is one fix, but the cleaner answer is to render the section server-side and not have it pop in at all.

Shopify's Section Rendering API lets you request a single section's rendered HTML from any URL. The pattern is ?section_id=related-posts appended to any request. You get back HTML, and you swap it into the DOM.

Why is this useful if Liquid already rendered the section server-side on the initial page load? Because you can do a two-pass approach:

  1. First paint: render with the cheap tag-only scoring directly in Liquid. The block exists in HTML, the links are crawlable, no CLS.
  2. Hydration: fetch the same section with a richer query (more candidate articles, optional author/keyword weighting) and replace the HTML. The swap is identical layout, no shift.

Or, simpler: render once server-side with the full algorithm and never touch the DOM after. That's what I do for most installs. The Section Rendering API still matters because it's how you re-render the block in a wishlisted or AJAX-y context without reloading the page.

Here's the fetch:

async function loadRelatedPosts(articleHandle, container) {
  const url = `/blogs/news/${articleHandle}?section_id=related-posts`;

  try {
    const res = await fetch(url, {
      headers: { 'Accept': 'text/html' }
    });
    if (!res.ok) throw new Error(`HTTP ${res.status}`);

    const html = await res.text();
    // The section response is wrapped in a div with the section id.
    const parser = new DOMParser();
    const doc = parser.parseFromString(html, 'text/html');
    const fresh = doc.querySelector(`#shopify-section-related-posts`);

    if (fresh && container) {
      container.replaceWith(fresh);
    }
  } catch (err) {
    console.warn('Related posts refresh failed', err);
    // Leave the server-rendered block in place. Graceful degradation.
  }
}

Enter fullscreen mode Exit fullscreen mode

Two things worth flagging. The URL has to be a valid Shopify URL — you can hit the article URL itself, or /, or any path that includes the section in its template. Different themes scope sections differently; you'll want to test which path includes your section. And the response is HTML, not JSON. There's no section.id.json endpoint for blog sections the way there is for product sections in some setups. Parse the HTML, find your section's outer wrapper by ID, and swap.

Combined scoring

Putting it together, here's the scoring function I land on for most stores. Tag overlap is the spine. Author is a tiebreaker. Keywords are the fine-grain.

const STOPWORDS = new Set([
  'the','a','an','and','or','of','to','in','on','for','with',
  'is','are','was','were','be','been','it','this','that','your','you'
]);

function tokenize(text) {
  return text
    .toLowerCase()
    .replace(/[^a-z0-9\s-]/g, ' ')
    .split(/[\s-]+/)
    .filter(t => t.length > 2 && !STOPWORDS.has(t));
}

function jaccard(setA, setB) {
  const a = new Set(setA);
  const b = new Set(setB);
  const intersection = [...a].filter(x => b.has(x)).length;
  const union = new Set([...a, ...b]).size;
  return union === 0 ? 0 : intersection / union;
}

function scoreArticle(current, candidate) {
  const tagScore = jaccard(current.tags, candidate.tags);

  const authorScore = current.author === candidate.author ? 1 : 0;

  const currentTokens = tokenize(
    `${current.title} ${current.handle}`
  );
  const candidateTokens = tokenize(
    `${candidate.title} ${candidate.handle}`
  );
  const keywordScore = jaccard(currentTokens, candidateTokens);

  return (
    tagScore * 0.5 +
    authorScore * 0.2 +
    keywordScore * 0.3
  );
}

function rankRelated(current, candidates, limit = 3) {
  return candidates
    .filter(c => c.handle !== current.handle)
    .map(c => ({ ...c, _score: scoreArticle(current, c) }))
    .filter(c => c._score > 0)
    .sort((a, b) => b._score - a._score)
    .slice(0, limit);
}

Enter fullscreen mode Exit fullscreen mode

Weights are tunable. I've ended up at 0.5 / 0.2 / 0.3 because tags are the highest-signal feature on a well-tagged blog, but keywords pull more weight when tags are sparse. If you have a content audit step, you can A/B these — track click-through on the related-posts block as your success metric and adjust. The fallback when every score is 0 (an article with unique tags, unique author, no shared keywords) is to surface the latest few posts. That's the only legitimate use case for the "latest 3" widget — as a fallback, not as a default.

What I'd avoid

A few patterns I've seen on stores I've looked at that don't work:

Random shuffle. Some themes ship with "related posts" that are actually just blog.articles | shuffle | limit: 3. It's worse than latest-3 because at least latest-3 surfaces fresh content. Random surfaces archive posts that the merchant has probably stopped maintaining.

Pure JS rendering with no SSR fallback. Pretty common in older "related posts" apps. Block injects on DOMContentLoaded, Googlebot mostly ignores it, internal-link equity wasted, CLS hit. If you're doing this in 2026, stop.

Showing more than 3 or 4. Diminishing returns. The fourth and fifth items get clicks in the low single digits in the merchant data I've looked at. Real estate is better spent on a newsletter signup or a product card.

Scoring against every article. Cap the candidate set. The most recent 50 is plenty for any reasonable blog. If you genuinely have a 5000-article archive, build a separate batch job that pre-computes related posts and stores them in metafields. That's a different post though.

What shipping it taught me

A few things I didn't expect.

Most merchants under-tag. Their articles have one or two tags total, and Jaccard scores are mostly 0 or 0.5. The author and keyword signals carry more weight in practice than they should in theory. If you're building this for a single store, audit the tagging first — you'll get more lift from cleaning tags than from tweaking weights.

Carousels test worse than grids on mobile, from what I've seen. People scroll past carousels because they look like ads. A 2x2 grid that all renders above the fold of the post-article scroll position outperforms a swipeable carousel in the click-through data I've had access to. Hedge: this is from a handful of stores, not a controlled study. Try both.

The Section Rendering API approach saved me from a CLS regression on one store that was running a Liquid-rendered block but with images that loaded after first paint. Adding explicit width and height on the related-post thumbnails matters at least as much as the rendering pattern itself. Reserve the space.


I made an app for this — Better Related Blog Posts — if you'd rather not roll your own. It's on the App Store and it does the tag/author/keyword scoring plus the layouts (grid, list, carousel) on a Theme App Extension so there's no script tag and nothing to maintain. Happy to share more about how it's built if useful. But honestly, if you're comfortable in Liquid and JS, everything above is enough to build the V1 yourself in an afternoon. The hard part isn't the algorithm — it's getting the tagging clean enough that the algorithm has signal to work with.