Building a “Lightweight Knowledge Index” for the Blog (Part 8): Right Sidebar Menu—A Unified Organization Mechanism for Semantic Space and Taxonomy
Article Abstract
To address the low reach of recommended content on the blog, a right-side floating menu solution based on semantic similarity and category systems was designed. By offline generating article semantic vectors and category semantic spaces, combined with WordPress front-end dynamic rendering, continuous exposure of recommended content is achieved in a prominent position without interfering with the reading experience. Utilizing the hierarchical data structures of embedding-index.json and category-space.json, this solution upgrades categories from static tags to semantic aggregates, expanding the recommendation logic from “article → article” to a structured path of “article → category → article”, ultimately forming a more multi-dimensional knowledge network and enhancing user exploration depth and content relevance.
Qwen3-14B · 2026-07-01

1 Introduction

In the previous articles of this series, I added “Related Articles” (see:Building a “Lightweight Knowledge Index” for My Blog (Part 3): Design and Implementation of a Lightweight WordPress Recommendation System Based on Pre-computed Semantic Index) and “Guess What You Think” features at the bottom of the article page to recommend content based on different dimensions after visitors finish reading a single post:

image.png

Among them, “Related Articles” leans more toward structured relationships, such as content continuation or upstream/downstream associations under the same topic; whereas “Guess What You're Thinking” relies more on semantic similarity, using embedding vector calculations to find articles that are close in the semantic space.

The original intention of this design was to make the blog system more than just a “collection of content,” but rather to establish horizontal connections between articles, allowing knowledge to unfold in a network-like manner, thereby enhancing overall explorability and, in turn, reducing the user bounce rate.

However, in actual observation, I gradually realized a problem: relying solely on the recommendation mechanism at the end of the article actually has limited coverage. The reality is that many visitors do not read an entire article, let alone scroll to the bottom of the page to view recommended content. Therefore, these carefully designed related recommendations actually have a low reach rate, and in many visit scenarios, they feel more like a structure that “exists but is not used.”

Based on this issue, I began to rethink the display hierarchy of the recommendation system: Does it have to rely on the end of the article? Is there a more frequent, more prominent, yet non-intrusive position that won't interfere with the reading experience?

While observing the page layout, I noticed the blank area on the right side of the article page—especially after the Argon theme disabled the sidebar widgets, this area was almost completely idle:

image.png

Yet visually, it lies at the natural boundary of the user's reading field of view, making it highly suitable for carrying some “auxiliary information.”

So I tried to introduce a floating related recommendation component in this position. It no longer waits for the user to finish reading the article, but continuously exists during the reading process, serving as an “always-accessible entry point to knowledge.”

So, what logic should this entry point use to organize content? At this point, I returned to a core structure that already existed in the blog:Blog Knowledge Mapthe category system. These categories themselves are not simple tags, but organized thematic aggregation structures, which are essentially already a higher-level dimension of knowledge organization. If combined with the semantic similarity between articles, a dual filtering mechanism of “category × semantic space” can be formed.

Therefore, this right-side floating menu was ultimately defined as ”a dynamic related recommendation layer that aggregates and ranks within the existing category structure based on article semantic similarity.” Its role is no longer simply to “recommend the next article,” but to provide a more structured entry point: allowing users to start from the current reading content and horizontally expand their reading path within the category dimension.

In a sense, this layer of structure makes up for the deficiency in “exposure position” of the recommendation mechanism that originally only existed at the bottom of the article, making the entire blog's content network more multi-dimensional and closer to an explorable knowledge system rather than a linear list of articles.

2 Design

1 Design Concept of the Right-Side Menu

Actually, the initial goal was not the right-side menu; the earliest goal was to build an in-site semantic search system based on semantic vectors—so that the association between articles no longer relies on traditional tags or categories, but is instead directly determined by the distance in the embedding space to decide recommendation relationships.

However, during the actual implementation, a key constraint was quickly encountered: the model used to generate embeddings (qwen3-embedding:8b) is deployed in an intranet environment and is not suitable for direct exposure to public network services. If I insisted on doing “real-time semantic search,” it would mean bringing the entire vector generation capability online, which is not a great choice under the current deployment structure—even if published to the public network via Cloudflare Tunnel, the access speed from within China wouldn't be very fast. Of course, using a paid cloud API is an option, but I'm not willing to spend money~.

This limitation, in turn, prompted me to rethink “where the semantic capability should be placed”—since real-time calculation is impossible, I had to take a step back and move the semantic calculation forward to the offline stage, which means calculating and solidifying all article vectors in advance, and then only performing lightweight similarity calculations and aggregations during front-end requests.

In fact, when implementing the “Guess What You Think” feature previously, I already had an embedding-based implementation and had generated a semantic-vector.json. However, that version of the data structure was more geared towards single-article-level semantic indexing, with an overall organization of a flat “article → vector” structure. This would expose some issues when used for cross-category aggregation, such as inconsistent data granularity and the need for an additional structural reorganization when expanding category dimensions later. Therefore, at this stage, I chose not to directly reuse the old structure, but instead rebuilt an article-level system “embedding-index” oriented towards ”category relationship calculation,” leaving room for subsequent category-level semantic modeling.

With article-level embeddings in place, the next step became quite natural: since similarity between articles can be calculated via vectors, categories can also be viewed as “semantic aggregates of article collections.” Specifically, each category is no longer just a static tag, but can have a ”semantic center vector” representing that category calculated from the vectors of its representative articles. When a user visits a certain article, the similarity between the current article's vector and each category's vector can be calculated first, thereby obtaining the top set of categories that are semantically closest.

After determining the most relevant categories (after comprehensive consideration, I felt that 3 categories was the most appropriate), and then further performing article-level similarity ranking within these categories (a quick decision confirmed that 4 articles was the most appropriate), a hierarchical recommendation result can be obtained: first, the “Top 3 categories most relevant to the current article,” and then the “Top 4 semantically closest articles” under each category. In this way, recommendations are no longer just matches between single articles, but form a two-level semantic structure of “article → category → article.”

Overall, the essence of this right-side menu is not a simple navigation component, but rather explicitly exposing the “semantic organizational structure” originally hidden in the background to the user interface, making categories no longer just information archiving tools, but a dynamic dimension of content association.

2 Data Structure and System Input: The Semantic Organization Foundation Composed of Three Types of JSON

After clarifying the design concept of the right-side menu, the system implementation actually relies on a set of data structures generated layer by layer. These structures do not exist in isolation, but are built step-by-step along the path of “content generation → semantic expression → structural aggregation,” ultimately forming the complete data foundation for the right-side menu.

Overall, this system mainly relies on three core JSON files, which are at different semantic levels and have clear generation dependencies.

embedding-index.json

First is the data source of the article semantic layer, corresponding to embedding-index.json. The data at this layer is not directly generated from the articles, but is built on top of the JSON files output from the previous article about “AI Summary” (see:Building a “Lightweight Knowledge Index” for My Blog (Part 6): AI Summary and Editable Semantic Layer Design). Specifically, it relies on two intermediate products: summary-source.json and summary-index.json.

Among them, summary-source.json is responsible for providing the original semantic input of the article content, while summary-index.json performs structured organization and summary induction on this basis. embedding-index.json further generates vector representations on top of this semantic compression result, bringing every article into a unified semantic space.

From the perspective of data structure, a typical embedding-index.json structure is as follows:

{
  "14334": {
    "post_id": "14334",
    "url": "/technology/homedatacenter14334/",
    "title": "为博客构建“轻量级知识索引”(四):系列文章导航与阅读路径设计",
    "embedding": [0.008560282, -0.02900768, 0.013086175, ...],
    "control": {
      "roadmap_hint": null
    },
    "meta": {
      "summary": "针对博客系列文章阅读连续性不足的问题,通过构建轻量级知识索引实现结构化导航方案。基于article-index.json文件与标题规则提取系列标识和序号,无需新增数据库结构或插件依赖...",
      "updated": "2026-06-10 10:58:56",
      "model": "qwen3-embedding:8b",
      "content_hash": "df3b496a82d707594fd3b3433f70aebd1352d286303c1c9742b2a5e7e1e5fc42"
    }
  }
}

“14334”: {


“post_id”: "14334",

"url": "/technology/homedatacenter14334/",

“title”: "Building a 'Lightweight Knowledge Index' for Blogs (Part 4): Series Article Navigation and Reading Path Design",

"embedding": [0.008560282, -0.02900768, 0.013086175, ...],


"control": {

"roadmap_hint": null

},

From the perspective of data structure, its core form is as follows:

{
  "categories": [
    {
      "id": "infra",
      "name": "个人数字基础设施与博客系统构建",
      "articles": [
        {
          "title": "浅谈如何选择最适合你的NAS",
          "url": "/technology/nas602/"
        },
        {
          "title": "群晖NAS HDD数据硬盘自动休眠",
          "url": "/technology/nas139/"
        },
        {
          "title": "从零开始搭建个人博客之完整攻略(最低成本)",
          "url": "/technology/homedatacenter12540/"
        }
      ]
    }
  ]
}

“categories”: [

{

"id": "infra",

"name": "Personal Digital Infrastructure and Blog System Construction",

"articles": [

{

{
  "categories": [
    {
      "id": "infra",
      "name": "个人数字基础设施与博客系统构建",
      "embedding": [
        0.0108209606,
        -0.0248727239,
        0.0033332910,
        -0.0051341676
      ],
      "articles": [
        {
          "title": "浅谈如何选择最适合你的NAS",
          "url": "/technology/nas602"
        },
        {
          "title": "群晖NAS HDD数据硬盘自动休眠",
          "url": "/technology/nas139"
        },
        {
          "title": "从零开始搭建个人博客之完整攻略(最低成本)",
          "url": "/technology/homedatacenter12540"
        }
      ]
    }
  ]
}

"url": "/technology/nas602/"

},

{

"title": "Synology NAS HDD Data Hard Drive Auto-Sleep",

3 Overall System Architecture and Engineering Value

"url": "/technology/nas139/"

summary-source.json
        ↓
summary-index.json
        ↓
embedding-index.json
        ↓
        ├───────────────┐
        ↓               ↓
roadmap-source.json   (知识地图结构)
        ↓               ↓
        └──────┬────────┘
               ↓
      category-space.json
               ↓
        右侧菜单推荐系统

{

"title": "Complete Guide to Building a Personal Blog from Scratch (Lowest Cost)",

“url”: "/technology/homedatacenter12540/"

3 Engineering Implementation: From Offline Construction to Front-End Presentation

1 Overall Process of Engineering Implementation

}

] }This part is handled by the script ] }

Unlike the embedding layer, this layer does not involve any semantic computation; its role is to provide a stable structural boundary so that semantic recommendations do not deviate from the established content organization system. In other words, it defines "how blog content is organized" rather than "how content is semantically related." From a system design perspective, this layer is more like a "manually constructed knowledge skeleton." All semantic computations must be completed within this skeleton, thereby ensuring that recommendation results do not deviate from the blog's original knowledge structure.category-space.json The third layer is the category semantic space layer, corresponding to category-space.json.The data in this layer is the most critical fusion product of the entire system, relying on both roadmap-source.json and embedding-index.json.

From a structural perspective, its core form is as follows: From a system design perspective, this layer is more like a "manually constructed knowledge skeleton." All semantic computations must be completed within this skeleton, thereby ensuring that recommendation results do not deviate from the blog's original knowledge structure. {

"categories": [

2 Article Semantic Vector Generation: build_embedding_index.py

{

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
import os
import time
import requests
import hashlib

# -----------------------------
# Ollama embedding 服务(需根据实际场景修改)
# -----------------------------
OLLAMA_URL = "http://127.0.0.1:11434/api/embed"
MODEL_NAME = "qwen3-embedding:8b"

# -----------------------------
# 路径配置(需根据实际场景修改)
# -----------------------------
CACHE_DIR = "/docker/wordpress/html/wp-content/themes/argon-theme-master/cache/"
SUMMARY_FILE = os.path.join(CACHE_DIR, "summary-index.json")

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
SOURCE_FILE = os.path.join(SCRIPT_DIR, "summary-source.json")
OUTPUT_FILE = os.path.join(CACHE_DIR, "embedding-index.json")

# -----------------------------
# 工具函数
# -----------------------------
def load_json(path, default):
    if not os.path.exists(path):
        return default
    with open(path, "r", encoding="utf-8") as f:
        return json.load(f)


def make_hash(text):
    return hashlib.sha256(text.encode("utf-8")).hexdigest()


# -----------------------------
# embedding 请求
# -----------------------------
def get_embedding(text, retries=3):
    payload = {
        "model": MODEL_NAME,
        "input": text
    }

    for i in range(retries):
        try:
            resp = requests.post(
                OLLAMA_URL,
                json=payload,
                timeout=180
            )

            if resp.status_code == 200:
                data = resp.json()
                emb = data.get("embeddings", [])
                if emb:
                    return emb[0]

        except Exception as e:
            pass

        time.sleep(2 * (i + 1))

    return None


# -----------------------------
# 轻量规则(预留结构信息)
# -----------------------------
def infer_roadmap_hint(text):
    t = text.lower()

    if "cloudflare" in t:
        return "cloudflaremap"
    if "embedding" in t or "ai" in t or "llm" in t:
        return "aimap"
    if "music" in t or "sound" in t:
        return "singmap"

    return None


# -----------------------------
# 主流程
# -----------------------------
def main():
    source = load_json(SOURCE_FILE, [])
    summary = load_json(SUMMARY_FILE, {})
    cache = load_json(OUTPUT_FILE, {})

    for article in source:
        post_id = str(article.get("id"))
        if not post_id or post_id in cache:
            continue

        summary_item = summary.get(post_id)
        if not summary_item:
            continue

        title = summary_item.get("title", "")
        summary_text = summary_item.get("summary", "")
        url = article.get("url", "")

        embedding_input = title + "\n" + summary_text
        embedding = get_embedding(embedding_input)

        if not embedding:
            continue

        cache[post_id] = {
            "post_id": post_id,
            "url": url,
            "title": title,
            "embedding": embedding,
            "control": {
                "roadmap_hint": infer_roadmap_hint(title + " " + summary_text)
            },
            "meta": {
                "summary": summary_text,
                "model": MODEL_NAME
            }
        }

        with open(OUTPUT_FILE, "w", encoding="utf-8") as f:
            json.dump(cache, f, ensure_ascii=False, separators=(',', ':'))


if __name__ == "__main__":
    main()

Functionally speaking, this script mainly accomplishes three things:Reading article summary data, calling the embedding model to generate semantic vectors, and outputting a JSON index file with a unified structure。

The most critical part is not the embedding call itself, but the unification process of the entire data structure. At this stage, the system no longer directly processes the original WordPress article content, but instead relies on the output generated in the previous stage summary-source.json 和 summary-index.json, concatenating the article title and summary as semantic input to generate a stable vector representation.

The final output }, where each record contains the following core fields:

  • post_id: Unique identifier of the article
  • url: Article link path
  • title: Article title
  • embedding: Article semantic vector (core field)
  • control.roadmap_hint: Lightweight structural hint (used for weak classification assistance)
  • meta.summary: Article summary information
  • meta.model: Identifier of the embedding model used

From a system perspective, the significance of this step is:Unify and convert the text information originally scattered across WordPress and the summary system into computable semantic space data. All subsequent category aggregation and recommendation logic are built directly on top of this embedding index.

3 Category Semantic Space Generation: build_category_space.py

With the article-level semantic vectors in place, the next step is to use the build_category_space.py script to further converge these “point-like article semantics” into a “category-level semantic space”, which is ultimately used for the right-side menu recommendations From a system design perspective, this layer is more like a "manually constructed knowledge skeleton." All semantic computations must be completed within this skeleton, thereby ensuring that recommendation results do not deviate from the blog's original knowledge structure., and the script code is as follows:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity

# =========================
# Config
# =========================

ROADMAP_FILE = "roadmap-source.json"

CACHE_DIR = "/docker/wordpress/html/wp-content/themes/argon-theme-master/cache/"

EMBEDDING_FILE = CACHE_DIR + "embedding-index.json"
OUTPUT_FILE = CACHE_DIR + "category-space.json"

MODE = "hybrid"   # struct | semantic | hybrid
ALPHA = 0.4       # struct weight

# =========================
# Utils
# =========================

def load_json(path):
    with open(path, "r", encoding="utf-8") as f:
        return json.load(f)


def l2_normalize(vec):
    arr = np.array(vec, dtype=np.float32)

    if arr.ndim == 1:
        norm = np.linalg.norm(arr)
        return arr / (norm + 1e-10)

    norm = np.linalg.norm(arr, axis=1, keepdims=True)
    return arr / (norm + 1e-10)


def normalize_url(url: str):
    if not url:
        return url
    return url.rstrip("/")


def struct_weight(title: str):
    w = 1.0

    if any(x in title for x in ["(一)", "(二)", "(三)", "(四)", "Part", "系列"]):
        w += 0.2

    if any(x in title for x in ["架构", "系统", "设计", "重构", "方案"]):
        w += 0.3

    if len(title) < 18:
        w -= 0.2

    return max(w, 0.5)


def build_embedding_map(embedding_data):
    emb_map = {}

    for post_id, item in embedding_data.items():

        if not isinstance(item, dict):
            continue

        url = normalize_url(item.get("url"))
        embedding = item.get("embedding")

        if not url or not embedding:
            continue

        emb_map[url] = l2_normalize(embedding)

    return emb_map


def build_category_groups(roadmap):
    groups = {}

    for cat in roadmap["categories"]:
        groups[cat["id"]] = {
            "id": cat["id"],
            "name": cat["name"],
            "articles": cat["articles"]
        }

    return groups


def semantic_weights(embeddings):
    if len(embeddings) == 0:
        return []

    embs = np.array(embeddings)

    if len(embs) == 1:
        return [1.0]

    mean = np.mean(embs, axis=0).reshape(1, -1)
    sims = cosine_similarity(embs, mean).flatten()

    denom = sims.max() - sims.min()
    if denom < 1e-10:
        return [1.0] * len(sims)

    sims = (sims - sims.min()) / denom
    return 0.5 + sims


def compute_centroid(embeddings, weights):
    if len(embeddings) == 0:
        return None

    embeddings = np.array(embeddings)
    weights = np.array(weights).reshape(-1, 1)

    centroid = np.sum(embeddings * weights, axis=0) / (np.sum(weights) + 1e-10)

    return l2_normalize(centroid).tolist()


def build():
    roadmap = load_json(ROADMAP_FILE)
    embedding_data = load_json(EMBEDDING_FILE)

    emb_map = build_embedding_map(embedding_data)
    categories = build_category_groups(roadmap)

    output = {"categories": []}

    for cid, cat in categories.items():

        embs = []
        struct_ws = []
        articles_out = []

        for a in cat["articles"]:
            url = normalize_url(a["url"])

            if url not in emb_map:
                continue

            emb = emb_map[url]

            embs.append(emb)
            struct_ws.append(struct_weight(a["title"]))

            articles_out.append({
                "title": a["title"],
                "url": url
            })

        if len(embs) == 0:
            continue

        embs_np = np.array(embs)
        sem_ws = semantic_weights(embs_np)

        n = len(embs)
        struct_ws = struct_ws[:n]
        sem_ws = sem_ws[:n]

        if MODE == "struct":
            final_ws = struct_ws
        elif MODE == "semantic":
            final_ws = sem_ws
        else:
            final_ws = [
                ALPHA * sem_ws[i] + (1 - ALPHA) * struct_ws[i]
                for i in range(n)
            ]

        centroid = compute_centroid(embs_np, final_ws)

        output["categories"].append({
            "id": cid,
            "name": cat["name"],
            "embedding": centroid,
            "articles": articles_out
        })

    with open(OUTPUT_FILE, "w", encoding="utf-8") as f:
        json.dump(output, f, ensure_ascii=False, indent=2)


if __name__ == "__main__":
    build()

Functionally, what this script does can actually be summarized in one sentence:Compress “article semantic vectors” into “category semantic vectors”. Its input comes from two parts: one is generated in the previous section, }, which stores the semantic vector of each article; the other is roadmap-source.json, which is the blog knowledge map, providing the category structure and the list of articles under each category.

During processing, the script first converts } into a vector map indexed by URL. The purpose of this step is to allow “articles in a category” to quickly find their corresponding semantic vectors. Meanwhile,roadmap-source.json will be parsed into category structure data to determine which articles each category contains.

Next, the system performs aggregation calculations on the article vectors within each category. Instead of a simple average, a weighting mechanism is introduced: it considers both semantic similarity (semantic weight) and article structural features (struct weight), such as whether it belongs to a series of articles, or whether it leans towards architecture design content.

Ultimately, each category is compressed into a “semantic centroid vector (centroid)”, while retaining a list of representative articles under that category. This is the core content of the final output From a system design perspective, this layer is more like a "manually constructed knowledge skeleton." All semantic computations must be completed within this skeleton, thereby ensuring that recommendation results do not deviate from the blog's original knowledge structure. .

From the results, once this step is completed, the “categories” in the system are no longer just directory structures in WordPress, but have become semantic entities that can participate in similarity calculations, providing a foundation for the subsequent recommendation logic of the right-hand menu.

4 WordPress Right-Side Menu Implementation: Front-End Rendering and Semantic Recommendation Landing

4.1 Front-End Architecture Split: Division of Responsibilities for PHP / JS / CSS

This part is the truly “visible” end of the entire system, which is the actual presentation of the right-hand floating menu on the WordPress page. Compared to the previous chapters focusing on data structures and engineering generation, the focus of this part has shifted from “how to calculate semantics” to “how to stably and cost-effectively present the generated semantic results on the front end.”

In terms of implementation structure, this module is split into three parts: PHP (server-side computation and data organization layer), JavaScript (front-end interaction and state control layer), and CSS (visual presentation layer). This split is not simply determined by the WordPress execution model, but naturally formed by the system's own responsibility boundaries—namely, the need to separate “deterministic computation” from “interactive state management” while keeping the front end lightweight and stateless.

Through this splitting method, the system logically forms three clear layers of responsibility boundaries, allowing recommendation computation, interaction control, and visual presentation to be decoupled from each other, thereby reducing the complexity and maintenance cost of the overall system.


In this structure, the role of the PHP part is the “data entry + online recommendation computation layer.” It is responsible for injecting the HTML container of the right-hand menu into the article page, and loading From a system design perspective, this layer is more like a "manually constructed knowledge skeleton." All semantic computations must be completed within this skeleton, thereby ensuring that recommendation results do not deviate from the blog's original knowledge structure. 与 } and other offline-generated data files, while performing in-category similarity calculations, candidate article sorting, and filtering rule applications (such as self-similarity filtering and series deduplication) on the server side based on the current article's embedding vector.

It can be understood as: PHP at this layer is not just a simple data mover, but assumes the responsibility of “online deterministic recommendation computation based on pre-computed semantic space,” and finally passes the computed results to the front-end JavaScript.

The JavaScript part is the interaction and display control layer of the entire right-hand menu. It is responsible for reading the structured data object injected into the page by PHP window.SIDEBAR_DATA, which contains not only the From a system design perspective, this layer is more like a "manually constructed knowledge skeleton." All semantic computations must be completed within this skeleton, thereby ensuring that recommendation results do not deviate from the blog's original knowledge structure. category structure in, but also the final recommendation results calculated by PHP at runtime based on the current article's embedding.

At the rendering level, JS dynamically generates and inserts the category list and corresponding article list into the DOM, thereby building the complete UI structure of the right-hand menu. At the interaction level, by listening to mouse hover and enter/leave behaviors, it controls state transitions between category switching and article panel display, implementing a lightweight UI state machine. Note that this layer does not participate in any similarity calculations or sorting logic; the responsibility of JS is strictly limited to converting the “already computed recommendation structure” into a user-interactive interface presentation.

The CSS part focuses entirely on the visual presentation layer and does not participate in any logical processing. It is mainly responsible for the layout structure, hierarchical relationships, animation effects, and visual feedback under hover states of the right-hand floating menu, ensuring that the component has sufficient visibility on the page without interfering with the main text reading experience.


Through this three-layer split, the entire right-hand menu system is built as a clear layered structure in WordPress: PHP is responsible for embedding-based online similarity calculations, in-category sorting, filtering rule applications, and the organization and output of final recommendation results; JavaScript is responsible for converting the structured recommendation results output by PHP into front-end interactive UI state transitions; CSS is responsible for the final visual presentation and interaction feedback.

The core value of this design lies in the fact that it completely converges “semantic recommendation computation” to the server side, so that the front end no longer bears any computation or decision-making logic, thereby maintaining the lightweight and deterministic nature of the UI layer. Meanwhile, the recommendation logic no longer depends on the WordPress rendering lifecycle, but exists as an independent computation module, interacting with the front end solely through structured data.

From a system perspective, this split is not a simple separation of front-end and back-end, but a lightweight semantic architecture of “decoupling computation and expression,” allowing recommendation capabilities to evolve independently without affecting the stability of the content system itself.

4.2 WordPress-Side Data Construction and Recommendation Logic Implementation (PHP)

This part is the server-side computation and data assembly layer of the right-hand menu in WordPress. Its responsibility is not only to receive basic data such as the offline-generated embedding and category-space, but more importantly, to perform similarity calculations based on the current article vector during the page request phase, and complete in-category sorting, filtering, and recommendation result generation.

In other words, this layer undertakes both the “hosting and organization of the offline semantic space” and the “online recommendation computation based on the current context,” ultimately encapsulating the computation results into structured data (SIDEBAR_DATA) for use by the front-end JavaScript.

Looking at the overall structure, this PHP code mainly does three key things: unifying data access paths, building the semantic baseline of the current article, and generating the final category recommendation results for front-end display.

First, in the data preparation phase, the system loads } 和 From a system design perspective, this layer is more like a "manually constructed knowledge skeleton." All semantic computations must be completed within this skeleton, thereby ensuring that recommendation results do not deviate from the blog's original knowledge structure.from the cache directory. The former provides the vector representation of each article, while the latter provides the category space and its collection of articles. During the loading process, PHP normalizes the article URLs to ensure that data from different sources can be matched under the same indexing system.

On this basis, the system builds two key mapping relationships: one is the mapping of “article URL → embedding vector” for subsequent similarity calculations; the other is the mapping of “article URL → series information,” which originates from the title parsing logic in the article index data and is used to identify structural relationships between articles in the same series. The significance of this layer of design is that it not only considers semantic similarity but also introduces structural constraints to prevent content from the same series from repeatedly appearing in recommendations.

When obtaining the current article vector, the system first attempts to read it directly from the embedding mapping. If the current article does not have a corresponding vector (for example, due to missing index or abnormal situations), it falls back to using the global vector mean as an alternative baseline, thereby ensuring that the recommendation process can always run without system interruption due to missing single-point data.

Next, entering the core recommendation computation phase, the system iterates through the collection of articles under each category and calculates the cosine similarity between the current article vector and the candidate article vectors one by one. Standard cosine similarity is used here to measure proximity in the semantic space. During the calculation process, two key filtering mechanisms are introduced: first, “self-similarity filtering” to eliminate entries that are almost identical to the current article; second, “same-series filtering” to prevent the same content series from repeatedly appearing in the recommendation list.

After completing the preliminary screening, the system sorts the candidate articles based on similarity and further introduces a diversity control mechanism to prevent the recommendation results from being dominated by a single topic or a single structural sequence. Specifically, the system directly filters out all content belonging to the same series as the current article, thereby ensuring that the recommendation results maintain a “cross-series distribution” in terms of content structure. On this basis, each category retains at most 4 representative articles, and the average similarity of the candidate articles is used as the overall weight of that category for subsequent sorting.

After the weight calculation and sorting of all categories are completed, the system finally selects the Top 3 categories as the first-layer display content of the right-hand menu, used to construct the user's semantic entry space.

During the WordPress rendering phase, these results are generated within the post lifecycle and output to the frontend along with the page: on one hand, PHP integrates the pre-computed semantic data (embedding similarity results, category-space classification space, and series rule information) into the final recommendation structure; on the other hand, the HTML container required for the right-side menu is injected into the page, and through window.SIDEBAR_DATA exposed to the frontend JavaScript.

The frontend JavaScript only needs to read this structured data to complete the interactive rendering of category displays and post lists, without needing to participate in any semantic computation or data generation processes.

From the perspective of implementation positioning, this PHP layer is not an independent recommendation engine, but rather a “semantic result combination layer”: it is responsible for the lightweight fusion of the offline-built embedding index with the category semantic space, and combines the context of the current post to complete the final candidate filtering and structural organization, thereby achieving stable semantic recommendation capabilities without introducing independent backend services.

The specific PHP code is as follows:

// ======================================================
// ① URL normalize
// ======================================================
function sidebar_normalize_url(url) {path = parse_url(url, PHP_URL_PATH);
    return rtrim(path ?? '', '/');
}

// ======================================================
// ② cosine similarity
// ======================================================
function sidebar_cosine(a,b) {
    dot = 0;na = 0;
    nb = 0;n = min(count(a), count(b));

    for (i = 0;i < n;i++) {
        dot +=a[i] *b[i];na  += a[i] * a[i];
        nb  +=b[i] *b[i];
    }

    returndot / (sqrt(na) * sqrt(nb) + 1e-10);
}

// ======================================================
// ③ series extractor(完全复用成功逻辑)
// ======================================================
function sidebar_extract_series_info(title) {title = trim(str_replace(' ', ' ', title));

    // 中文括号版本
    if (preg_match('/^(.*?)[((]([一二三四五六七八九十百零]+)[))]/u',title, matches)) {series_key = trim(matches[1]);map = [
            '一'=>1,'二'=>2,'三'=>3,'四'=>4,'五'=>5,
            '六'=>6,'七'=>7,'八'=>8,'九'=>9,'十'=>10
        ];

        index_cn =matches[2];
        index =map[index_cn] ?? 0;

        if (index > 0) {
            return [
                'series_key' => series_key,
                'series_index' =>index
            ];
        }
    }

    // Part N 版本
    if (preg_match('/^(.*?)(?:Part\s*|part\s*|\()(\d+)\)?/u', title,matches)) {

        return [
            'series_key' => trim(matches[1]),
            'series_index' => intval(matches[2])
        ];
    }

    return null;
}

// ======================================================
// ④ 从 article-index.json 构建 series map(关键)
// ======================================================
function sidebar_build_series_map_from_articles() {

    file = get_template_directory() . '/cache/article-index.json';

    if (!file_exists(file)) return [];

    articles = json_decode(file_get_contents(file), true);
    if (!articles) return [];map = [];

    foreach (articles asid => article) {

        if (empty(article['url']) || empty(article['title'])) continue;url = sidebar_normalize_url(article['url']);info = sidebar_extract_series_info(article['title']);

        if (info) {
            map[url] = info['series_key'];
        }
    }

    returnmap;
}

// ======================================================
// ⑤ 数据层(最终稳定版)
// ======================================================
function sidebar_build_data() {

    embedding_file = get_template_directory() . '/cache/embedding-index.json';category_file  = get_template_directory() . '/cache/category-space.json';

    embeddings = json_decode(file_get_contents(embedding_file), true);
    categories = json_decode(file_get_contents(category_file), true);

    if (!embeddings || !categories || !isset(categories['categories'])) {
        return null;
    }

    // embedding mapemb_map = [];

    foreach (embeddings asitem) {
        if (!isset(item['url'],item['embedding'])) continue;
        emb_map[sidebar_normalize_url(item['url'])] = item['embedding'];
    }

    // series map(来自 article-index.json ——关键修复点)series_map = sidebar_build_series_map_from_articles();

    current_url = sidebar_normalize_url(_SERVER['REQUEST_URI'] ?? '');
    current_vec =emb_map[current_url] ?? null;

    if (!current_vec) {

        all = array_values(emb_map);
        if (!all) return null;dim = count(all[0]);avg = array_fill(0, dim, 0);

        foreach (all as vec) {
            for (i = 0; i<dim; i++) {avg[i] +=vec[i];
            }
        }

        for (i = 0; i<dim; i++) {avg[i] /= count(all);
        }

        current_vec =avg;
    }

    current_series =series_map[current_url] ?? null;SELF_SIM_THRESHOLD = 0.985;

    categories_out = [];

    foreach (categories['categories'] as cat) {candidates = [];
        sum = 0;cnt = 0;

        foreach (cat['articles'] asa) {

            url = sidebar_normalize_url(a['url']);
            if (!isset(emb_map[url])) continue;

            vec =emb_map[url];score = sidebar_cosine(current_vec,vec);

            // ① 去自相似
            if (score>SELF_SIM_THRESHOLD) {
                continue;
            }

            // ② 🚨 彻底去同系列(基于 article-index.json)
            series =series_map[url] ?? null;

            if (current_series && series &&series === current_series) {
                continue;
            }candidates[] = [
                'title' => a['title'],
                'url'   =>a['url'],
                'score' => score,
                'series'=>series
            ];

            sum +=score;
            cnt++;
        }

        if (cnt === 0) continue;

        usort(candidates, fn(a,b) =>b['score'] <=> a['score']);

        // diversity(每个 series 只保留一个)final = [];
        used = [];

        foreach (candidates as item) {s = item['series'];

            if (s && isset(used[s])) continue;

            final[] = [
                'title' =>item['title'],
                'url'   => item['url'],
                'score' =>item['score']
            ];

            if (s)used[s] = true;

            if (count(final) >= 4) break;
        }

        if (!final) {final = array_slice(candidates, 0, 4);
        }categories_out[] = [
            'id' => cat['id'],
            'name' =>cat['name'],
            'score' => sum / max(cnt, 1),
            'articles' => final
        ];
    }

    usort(categories_out, fn(a,b) => b['score'] <=>a['score']);

    return array_slice(categories_out, 0, 3);
}

// ======================================================
// ⑥ UI
// ======================================================
function render_sidebar_html() {
?>
<div id="semantic-sidebar">
    <div class="ssb-panel">
        <div class="ssb-trigger">查看相关分类·3个匹配</div>
        <div class="ssb-level ssb-level-1"></div>
        <div class="ssb-level ssb-level-2" id="ssb-articles"></div>
    </div>
</div>
<?php
}

// ======================================================
// ⑦ WP Hook(必须保留)
// ======================================================
add_filter('the_content', function (content) {
    if (!is_single()) return content;data = sidebar_build_data();

    ob_start();

    if (data) {
        echo '<script>';
        echo 'window.SIDEBAR_DATA=' . json_encode(
            ['categories' =>data],
            JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
        );
        echo '</script>';
    }

    render_sidebar_html();
    sidebar = ob_get_clean();
    returncontent . $sidebar;
});

4.3 Right-Side Menu Interaction Logic Implementation (sidebar.js)

This part is the “interaction control layer” of the right floating menu when running on the front end, and the corresponding file is sidebar.js. Its role is not to generate data, nor does it participate in any semantic calculation, but rather to convert the structured data injected into the page by PHP (window.SIDEBAR_DATA) into interactive UI behaviors, thereby completing the final link of “data → vision → behavioral feedback”.

From the perspective of overall implementation, the logic of this JS can be broken down into three core steps: initialization rendering, category switching control, and floating state management.

First, in the initialization phase, the script reads the data structure generated and injected by PHP during the article lifecycle from the global variable window.SIDEBAR_DATA and locates two key DOM containers of the right menu: the level-1 category container (.ssb-level-1) and the article display panel (#ssb-articles). Subsequently, the script dynamically generates HTML based on the category data, rendering all categories as hoverable entry nodes. This step is essentially a typical data-driven DOM construction process and is executed only once during the initialization phase, thereby avoiding state pollution caused by repeated rendering.

After completing the basic rendering, the system enters the core interaction logic: category switching and article display. When a user hovers over a category node, JS captures the target node through the event delegation mechanism, locates the corresponding category from the data structure based on its data-id , and then calls showCategory() to dynamically render the article list under that category into the right floating panel. This process is completed by directly rewriting the DOM, thereby achieving instant switching between categories.

At the same time, the system also maintains a lightweight runtime state, including the currently active category ID (activeCatId) and a timer for delayed closing (hideTimer). The existence of these states is not to implement complex logic, but to ensure the stability of the hover interaction, avoiding flickering or accidental closing when the mouse moves quickly.

At the interaction control level, this version adopts a hybrid model of “hover trigger + state-driven”. When the mouse enters the sidebar area, it triggers openSidebar(), making the level-1 category container enter the active state (active class), thereby displaying the category list; when the mouse leaves the sidebar area, a short delay timer is started to execute the close operation, reducing accidental triggers and flickering during boundary movement.

In the category interaction part, when a user hovers over a category node, the system identifies the target node based on the event delegation mechanism, and matches the corresponding category data through data-id , and then calls showCategory() to update the content of the right article panel. Since the article panel uses a dynamic DOM rewriting strategy, each category switch directly replaces the currently displayed content.

Meanwhile, to ensure interaction continuity, the system adds a “close protection mechanism” to the article panel area: when the mouse enters the article panel, the delayed close timer is cleared to prevent the panel from being accidentally closed during reading; when the mouse leaves the article area, the close logic is restored and the internal state is reset.

It is particularly important to note that the initialization mechanism of this version has been extended from the traditional DOMContentLoaded mode to “Argon PJAX lifecycle-driven”. Through the window.pjaxLoaded hook, the system can re-execute the initialization logic after each PJAX page switch is completed, thereby ensuring that SIDEBAR_DATA remains synchronized with the current article context, and avoiding state residue issues caused by partial page replacement.

It must be emphasized that this layer still does not involve any recommendation calculation logic, nor does it participate in category sorting or similarity calculation. All semantic calculations and recommendation result generation have already been completed on the PHP side, and the responsibility of JavaScript is limited to display control and interaction response.

Overall,sidebar.js is more like a lightweight UI state controller based on the PJAX lifecycle. Through a minimal number of state variables and event listening mechanisms, it implements a stable floating menu interaction model, allowing the right menu to still possess clear and predictable behavioral semantics without relying on front-end frameworks.

The code for sidebar.js is as follows:

(function () {

    let initialized = false;

    function init() {

        const root = document.getElementById("semantic-sidebar");
        if (!root) return;

        const data = window.SIDEBAR_DATA;
        if (!data || !data.categories) return;

        const level1 = root.querySelector(".ssb-level-1");
        const panel  = root.querySelector("#ssb-articles");

        let activeCatId = null;
        let sidebarOpen = false;
        let hideTimer = null;

        // =========================
        // 防止重复初始化(同一 PJAX 生命周期内)
        // =========================
        if (initialized) return;
        initialized = true;

        // =========================
        // render categories
        // =========================
        level1.innerHTML = data.categories.map(cat =>
            `<div class="ssb-cat" data-id="{cat.id}">{cat.name}
            </div>`
        ).join("");

        // =========================
        // open sidebar
        // =========================
        function openSidebar() {
            sidebarOpen = true;
            level1.classList.add("active");
        }

        // =========================
        // close sidebar
        // =========================
        function closeSidebar() {
            sidebarOpen = false;
            level1.classList.remove("active");
            hidePanel();
        }

        // =========================
        // show articles
        // =========================
        function showCategory(cat) {

            activeCatId = cat.id;

            panel.innerHTML = cat.articles.map(a =>
                `<a href="{a.url}">{a.title}</a>`
            ).join("");

            panel.classList.add("active");
        }

        // =========================
        // hide articles
        // =========================
        function hidePanel() {
            panel.classList.remove("active");
            panel.innerHTML = "";
            activeCatId = null;
        }

        // =========================
        // hover entry
        // =========================
        root.addEventListener("mouseenter", () => {
            openSidebar();
        });

        // =========================
        // hover leave
        // =========================
        root.addEventListener("mouseleave", () => {

            hideTimer = setTimeout(() => {
                closeSidebar();
            }, 120);
        });

        // =========================
        // category hover
        // =========================
        level1.addEventListener("mouseenter", (e) => {

            const el = e.target.closest(".ssb-cat");
            if (!el) return;

            const catId = el.dataset.id;
            const cat = data.categories.find(c => c.id === catId);

            if (!cat) return;

            showCategory(cat);
        }, true);

        // =========================
        // panel protection
        // =========================
        panel.addEventListener("mouseenter", () => {
            clearTimeout(hideTimer);
        });

        panel.addEventListener("mouseleave", () => {
            hidePanel();
        });

    }

    // =========================
    // ⭐ 核心修复:Argon PJAX 生命周期入口
    // =========================
    window.pjaxLoaded = function () {

        // 每次 PJAX 页面切换都会执行这里
        initialized = false;
        init();
    };

    // =========================
    // 首次加载(非 PJAX)
    // =========================
    if (document.readyState === "loading") {
        document.addEventListener("DOMContentLoaded", init);
    } else {
        init();
    }

})();

At the same time, a separate piece of PHP code needs to be added to implement the call to sidebar.js:

add_action('wp_enqueue_scripts', function () {

    wp_enqueue_script(
        'semantic-sidebar',
        get_template_directory_uri() . '/cache/sidebar.js',
        array(),
        null,
        true
    );

});

Note: I have placed sidebar.js and other JSON files that need to be directly called by WordPress under WordPress's ”/wp-content/themes/argon-theme-master/cache/“ path.

4.4 Right-Side Menu Styling and Visual Presentation (CSS)

This part is the visual presentation layer of the right floating menu in WordPress pages, and the corresponding implementation file is the CSS stylesheet. Its role is not to participate in any interaction logic, nor does it involve data processing, but rather to convert the structured DOM generated by JS into a floating UI component with a sense of hierarchy and space, thereby completing the final “visual presentation” of the entire system.

From the perspective of overall structure, this part of CSS is mainly organized around three levels: the overall floating container (Sidebar Root), the level-1 category area (Level 1 Categories), and the level-2 article panel (Article Panel). Each layer bears different visual responsibilities, thereby forming a clear spatial hierarchical relationship.

First is the outermost container #semantic-sidebar, which uses position: fixed to be fixed in the middle of the right side of the page, and through transform: translateY(-52%) Achieves a vertical centering offset, maintaining a stable visual position across different screen heights. Visually, the entire component belongs to the “floating UI” layer, so a higher z-indexis set to ensure it is not covered by the main content.

Inside the container,.ssb-panel serves as the overall background and visual carrier. Through a semi-transparent background color and backdrop-filter , it achieves a frosted glass effect, combined with shadows and borders to form a lightweight yet layered card-style container. The design goal of this layer is “present but non-intrusive”—that is, minimizing visual intrusion on reading the main text while ensuring visibility.

The interaction entry part, .ssb-trigger , acts as the initial prompt area for the component, providing only a low-disturbance visual entry hint. It does not participate in the expansion logic itself, but merely provides lightweight visual guidance and adds a status indicator dot via a pseudo-element, allowing users to quickly recognize the existence of the component's functionality.

In terms of structural control, the first-level category container .ssb-level 's display logic is completely handed over to JS control, so CSS is only responsible for basic state definitions: hidden by default (display: none), and switching to display after JS adds .active . This design avoids conflicts between CSS hover and JS states, making the expansion behavior completely predictable.

The category item .ssb-cat is mainly responsible for providing interactive visual feedback, including hover highlighting, text truncation, and lightweight transition effects. The design goal of this layer is to ensure clear readability even when there are many categories, while avoiding visual clutter.

The second-level article panel #ssb-articles is the visually most complex part of the entire component. It is designed as a floating panel positioned relatively to the left of the category list, anchored in space via position: absolute so that it always maintains a spatial relationship with the current category when expanded. Its display and hiding also rely entirely on JS adding or removing the .active class, thereby avoiding jitter issues caused by hover triggers.

In the implementation of article items .ssb-articles a , a combination of “double-line truncation + fade-out mask” is adopted, controlling the text length via -webkit-line-clamp while using a mask gradient to prevent abrupt boundaries from text truncation. This approach maintains overall visual neatness while ensuring information density.

Overall, the core design principle of this CSS version is “weak interaction, strong structure.” All interactive behaviors are controlled by JS, and CSS is only responsible for expressing the visual results after state changes, thereby avoiding coupling issues between hover and script logic, making the entire right-side menu system more stable in behavior and more unified visually.

The CSS code is as follows (for the ”Additional CSS” section of the current WordPress theme):

/* =========================
   Root(保持不变)
========================= */
#semantic-sidebar {
    position: fixed;
    right: 16px;
    top: 50%;
    transform: translateY(-52%);
    z-index: 99999;
    width: 200px;
    font-size: 13px;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}

/* =========================
   Panel container(稳定视觉层)
========================= */
.ssb-panel {
    background: rgba(28, 30, 34, 0.72);
    color: #e8e8e8;
    border-radius: 12px;
    padding: 10px;

    box-shadow:
        0 10px 30px rgba(0,0,0,0.35),
        0 0 0 1px rgba(255,255,255,0.04);

    backdrop-filter: blur(12px) saturate(140%);
    -webkit-backdrop-filter: blur(12px) saturate(140%);

    border: 1px solid rgba(255,255,255,0.06);

    position: relative;
}

/* =========================
   Trigger(入口按钮)
========================= */
.ssb-trigger {
    padding: 10px 8px;
    background: rgba(255,255,255,0.06);
    border-radius: 10px;
    cursor: default;
    user-select: none;
    font-weight: 500;
    color: #ddd;

    display: flex;
    align-items: center;
    justify-content: center;

    position: relative;
}

.ssb-trigger::after {
    content: "";
    position: absolute;
    right: 10px;
    top: 50%;
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background: rgba(120, 180, 255, 0.6);
    transform: translateY(-50%);
    opacity: 0.6;
}

.ssb-trigger:hover {
    background: rgba(255,255,255,0.1);
    color: #fff;
}

/* =========================
   Level container(关键修复)
   ✔ 完全交给 JS 控制
========================= */
.ssb-level {
    display: none;   /* 默认隐藏 */
    margin-top: 10px;
}

/* JS 控制展开 */
.ssb-level-1.active {
    display: block;
}

/* =========================
   Category item
========================= */
.ssb-cat {
    padding: 7px 8px;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.15s ease;
    color: #cfcfcf;

    display: block;
    text-align: left;

    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.ssb-cat:hover {
    background: rgba(255,255,255,0.08);
    color: #fff;
}

/* =========================
   Level 2 panel(完全稳定)
========================= */
#ssb-articles {
    position: absolute;
    right: 100%;
    top: 0;

    width: 220px;
    margin-right: 10px;

    background: rgba(28, 30, 34, 0.75);
    border-radius: 12px;
    padding: 10px;

    box-shadow: 0 10px 28px rgba(0,0,0,0.45);

    backdrop-filter: blur(14px) saturate(150%);
    -webkit-backdrop-filter: blur(14px) saturate(150%);

    border: 1px solid rgba(255,255,255,0.06);

    display: none;
    pointer-events: auto;
}

/* JS 控制显示 */
#ssb-articles.active {
    display: block;
}

/* =========================
   Article items(2行限制)
========================= */
#ssb-articles a {
    position: relative;

    display: block;
    padding: 6px 8px;
    border-radius: 8px;

    color: #bdbdbd;
    text-decoration: none;

    line-height: 1.35;

    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;

    overflow: hidden;

    -webkit-mask-image: linear-gradient(
        to bottom,
        black 85%,
        transparent 100%
    );
    mask-image: linear-gradient(
        to bottom,
        black 85%,
        transparent 100%
    );
}

#ssb-articles a:hover {
    background: rgba(255,255,255,0.08);
    color: #fff;
    transform: none;
}

/* =========================
   cleanup
========================= */
.ssb-level-1 {
    padding-bottom: 0;
}

/* =========================
   移动终端上禁用右侧菜单
========================= */
@media (max-width: 768px) {
    #semantic-sidebar {
        display: none !important;
    }
}

Regarding Initialization Issues in PJAX Environments

It should be noted that the above implementation is based on the traditional page loading model by default, meaning that the JavaScript initialization logic is re-executed when switching pages.

However, if the website has PJAX (PushState + AJAX) or other refresh-free loading technologies enabled, the page switching process usually only replaces part of the DOM content instead of reloading the entire page. Therefore, relying on DOMContentLoaded or the logic that completes initialization upon the script's first execution will often only run once during the first page visit, and subsequent page switches will not trigger it again.

Taking the Argon theme as an example, its official documentation clearly states:

window.pjaxLoaded = function () {
    // 页面每次切换完成后执行
};

Therefore, when using PJAX themes like Argon, the component initialization logic needs to be mounted to the corresponding PJAX lifecycle hooks so that it re-executes after each page switch. For example, the final version in this article sidebar.js uses this approach:

window.pjaxLoaded = function () {
    initialized = false;
    init();
};

This way, whether the page is loaded for the first time or articles are switched via PJAX, the right-side menu can correctly read the corresponding SIDEBAR_DATA and complete re-initialization.

From an engineering perspective, this is actually not an issue with the right-side menu itself, but rather a frontend component lifecycle management issue in PJAX environments. Any custom module that relies on page initialization needs to be adapted according to the lifecycle hooks provided by the theme or framework.


4.5 Right-Side Menu Running Effect and Interaction Performance

After the entire system is loaded, only a lightweight floating entry component will appear on the right side of the page. In its initial state, this component does not expand the category list, nor does it display any article content. Its visual presence is deliberately minimized, keeping only a stable entry area to avoid interfering with reading the main text:

image.png

When the user moves the mouse to the right floating area, the system enters an interactive active state. At this point, the first-level category list is dynamically expanded and presented as a vertical list inside the floating box. The entire expansion process does not rely on complex animations, but is presented in a stable state-switching manner, keeping the interface behavior predictable:

image.png

In this state, users can directly trigger content switching by hovering the mouse over different categories. Each category corresponds to a semantic clustering result, below which a list of the top 4 recommended articles within that category is displayed:

image.png

As the user continues to move between categories, the right article panel instantly updates its content without any jitter in the overall layout or page displacement. The article list always maintains a fixed width and position, with only the content being replaced, thereby ensuring visual stability. This design makes the interaction closer to an “information preview switch” rather than a traditional menu expansion:

image.png

At the same time, when the mouse moves out of the sidebar area, the system triggers a delayed closing mechanism to avoid frequent flickering or sudden disappearance of the panel due to slight accidental touches. After the user completely leaves the interaction area, the category list and the article panel will return to their initial collapsed state as a whole.


4 Series Review and Evolution Outlook

If we look back at the “Building a Lightweight Knowledge Index for a Blog” series over a longer timescale, it is not actually a collection of implementations centered around a single feature, but is gradually answering a more fundamental question: how to transform blog content from an “independent collection of articles” into an “information structure that can be continuously reorganized by machines.”

In this process, each article seems to solve a relatively independent problem—related article recommendations, series cards, "guess what you think", AI summaries, and the right semantic menu—but if we abstract them to the same level, we can see that they share the same evolutionary path: from explicit structure, to implicit semantics, and finally to a computable way of content organization.

From the perspective of the overall structure, this series can be summarized into three progressively enhanced levels:

内容层:
WordPress 原始文章

结构层(信息组织系统):
相关文章 / 系列卡片 / 右侧菜单 / 分类体系 / series 关系

语义增强层:
Embedding 相似度计算 / AI 摘要 / 猜你所想(已删除)

Among them, the core of the change does not lie in the increase in the number of features, but in the gradual clarification of the boundary between the structural layer and the semantic layer. Early systems relied more on explicit rules (tags, categories, manual associations), while after the introduction of embedding, the relationships between content gradually began to shift from “human-defined” to “semantic computation-driven.”

In this system, the right semantic menu occupies a relatively special position: it does not introduce new semantic capabilities, but reorganizes the existing embedding similarity results and category space into an interactive entry point close to the user's browsing path. From a system perspective, it is more like a “mapping from semantic structure to the user entry layer” rather than an independent computation module.

If disassembled from the functional dimension:

  • “Related Articles” solves the local semantic neighborhood problem (embedding similarity)
  • “Series Cards” solves the strong structural sequence problem (explicit order)
  • “Guess What You Think” provides weak semantic inference capability (fuzzy matching, but since the right menu already includes its functionality, it has been deleted)
  • “AI Summary” provides content compression and readable expression
  • “Right Menu” builds a continuously accessible semantic entry and category navigation on top of the existing structure

From this perspective, this series is not a superposition of features, but a structural evolution gradually unfolding around different organizations and access methods of the same content.

At the same time, the system always maintains a clear engineering constraint: semantic computation is split into offline construction and runtime lightweight processing, with the WordPress frontend only undertaking data loading and presentation logic. This model allows the system to maintain scalability while still possessing low operating costs and stability.

But it is also after this stage that a boundary begins to become clear: the current system has completed the infrastructure of “semantic expression and structural organization,” but has not yet entered the stage of “semantic-driven content flow.”

In other words, the existing modules are already able to express the relationships between content well, but most of these relationships still stem from pre-computation and rule combinations, and have not yet formed a continuously evolving semantic generation mechanism.

If this series is placed in a longer evolutionary path, the work it has currently completed can be understood as the construction process of a foundational base: transforming blog content from isolated text into computable objects with a stable semantic structure.

On top of this base, there are still some natural evolutionary directions, such as:

  • Moving from article-level semantics to finer-grained content unit organization
  • Moving from static embedding similarity to dynamic ranking based on behavioral feedback
  • Moving from pre-computed indexes to local online update mechanisms
  • Moving from presentation-based recommendations to path-based content discovery

But these are already beyond the scope of the current stage's goals. Therefore, looking at the series as a whole, what these seven articles have truly accomplished is not a “collection of features,” but a relatively complete middle-layer design: introducing a stable, scalable, and low-cost semantic structural layer between content and presentation. The significance of this layer lies not only in functional enhancement, but in giving content the ability to be “reorganized” for the first time.

At this point, the “Building a Lightweight Knowledge Index for a Blog” series has completed a phased closed loop at the structural level.

📚 系列文章:为博客构建“轻量级知识索引”(8 / 10)

View Related Categories · 3 Matches
📌 Content Structure Prompt:
This content is part of the following knowledge map, where you can view the complete content path: AI Learning Map · WordPress Learning Roadmap。
📎 Related Articles
Share this article
The blog content is original, please indicate the source when reposting! The RSS address of the blog is:https://blog.tangwudi.com/feed, welcome to subscribe; if needed, you can join theTelegram Groupto discuss questions together.
No Comments

Send Comment Edit Comment


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗ
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
Kaomoji
Emoji
Little Dinosaur
Flower!
Previous
Next
       

👋 Welcome to “Wudi's Personal Blog”

Here, long-term exploration is mainly carried out around the following directions:

🧱 Personal Digital Infrastructure and Blog System Construction
☁️ Cloudflare and Network Architecture Practice
🧠 AI and Knowledge System Exploration
🛡️ Network Security and Access Optimization
🎵 Music and Sound Cognition
👁️ Cognitive Perspectives and Worldviews