Blog › Jekyll

Auto-injecting Jekyll categories from _posts folder paths

Eliminate manual Front Matter categories in Jekyll by using _posts subdirectories as the single source of truth via a custom Ruby :post_read hook plugin.

Auto-injecting Jekyll categories from _posts folder paths

Maintaining categories in both _posts/ subdirectories and YAML Front Matter inevitably leads to typos and drift. This post explains how to make _posts/ folder paths the single source of truth using a 15-line Jekyll Ruby hook plugin, along with the GitHub Actions and _drafts/ caveats you need to handle.

Tested with Jekyll 4.4, jekyll-theme-chirpy 7.6, and Ruby 3.4.

Why manual Front Matter categories drift

Once a Jekyll blog passes 30 or 40 posts, you naturally organize Markdown files into topic folders like _posts/Blog/Jekyll/2026-11-20-post.md. The catch is that Jekyll’s default behavior ignores subdirectories inside _posts/ when assigning categories. Unless you also repeat categories: [Blog, Jekyll] in every file’s Front Matter, those posts end up uncategorized.

Maintaining the same hierarchy in two places creates two recurring bugs:

  • Casing mismatches and typos: Writing Spring in one file and spring in another splits your archive into duplicate categories.
  • Folder-to-category drift: Moving a file from _posts/Spring/Feature/ to _posts/Spring/JPA/ without updating Front Matter leaves your repository layout out of sync with the rendered blog menu.

Jekyll’s built-in alternative—placing category folders above _posts/ (for example, blog/jekyll/_posts/2026-11-20-post.md)—scatters posts across dozens of top-level directories, making search, scripts, and navigation harder to manage.

ApproachFile browsing ergonomicsTypo & drift riskCustom plugin required
Manual Front Matter categoriesFairHigh (dual maintenance)No
Top-level folders (cat/_posts/)Poor (scattered across repo)LowNo
_posts/ subfolders + Ruby hookHigh (all posts under _posts/)None (disk is SSOT)Yes (_plugins/)

When not to use this plugin

Skip a custom _plugins/ hook if you deploy using GitHub Pages’ legacy branch-based build (--safe mode) and don’t want to switch to GitHub Actions, or if a single post regularly needs to belong to two unrelated category trees (a folder path naturally represents one hierarchy per file).


How it works: Jekyll’s build lifecycle and hook timing

A Jekyll build runs through six sequential phases: reset → read → generate → render → cleanup → write. Picking the right hook event is what makes this plugin work cleanly.

flowchart TD
    A["Read Markdown files (_posts/)"] --> B["site :post_read hook"]
    B --> C["Parse folder path & set categories"]
    C --> D["generate (build category archives)"]
    D --> E["Render HTML & write _site/"]

If you attach your logic to :posts, :pre_render, it runs too late. Both Chirpy’s /categories/ index page and jekyll-archives’s /categories/:name/ pages are constructed during the generate phase by reading site.categories—which is populated before rendering ever starts.

Registering on Jekyll::Hooks.register :site, :post_read runs immediately after Jekyll loads all posts into site.posts.docs and right before generate begins. Mutating post.data['categories'] here ensures that category archive pages, sidebar counts, post breadcrumbs, and JSON-LD metadata all see the exact same values.


Implementation: _plugins/category-folder-hook.rb

Create _plugins/category-folder-hook.rb in your repository:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# frozen_string_literal: true

# _plugins/category-folder-hook.rb
#
# Automatically populates post categories directly from the directory structure under `_posts/`.
# The folder names on disk are the Single Source of Truth for category names.
#
# Examples:
#   _posts/Spring/Feature/post.md          => categories: ["Spring", "Feature"]
#   _posts/Spring/Wanted-Challenge/post.md => categories: ["Spring", "Wanted-Challenge"]
#   _posts/Blog/Jekyll/post.md             => categories: ["Blog", "Jekyll"]
#   _posts/Dev/post.md                     => categories: ["Dev"]

Jekyll::Hooks.register :site, :post_read do |site|
  site.posts.docs.each do |post|
    rel_path = post.relative_path.sub(%r{^_posts/}, '')
    subdirs = rel_path.split('/')[0...-1]

    # Subdirectories directly dictate post categories as-is
    unless subdirs.empty?
      post.data['categories'] = subdirs
    end
  end
end

Here is what each line does:

  1. post.relative_path.sub(%r{^_posts/}, '') strips the leading _posts/ prefix (if you also run a multilingual build with collections_dir: en, strip %r{^(?:en/)?_posts/} instead—see Building a bilingual Jekyll Chirpy blog with dual builds).
  2. .split('/')[0...-1] splits the path segments and drops the final filename, leaving only the directory chain.
  3. If the post lives directly inside _posts/ (subdirs.empty?), the hook leaves any explicit Front Matter untouched. Both one-level (_posts/Dev/) and two-level (_posts/Blog/Jekyll/) hierarchies work identically.

With the plugin in place, omit categories from your post Front Matter and keep only tags:

1
2
3
4
5
6
---
title: "Auto-injecting Jekyll categories from _posts folder paths"
description: "Use _posts subdirectories as the single source of truth for Jekyll categories via a Ruby hook."
date: 2026-11-20 09:00:00 +0900
tags: [jekyll, chirpy, ruby, blog]
---

Verifying the generated categories locally

Build the site locally and inspect the generated /categories/ output to confirm every folder mapped as expected:

1
2
bundle exec jekyll build -d /tmp/_site
ls /tmp/_site/categories/

You should see a slugified directory for every parent and child folder under _posts/ (for example, blog/, jekyll/, spring/, jpa/), with no leftover duplicates caused by casing typos.


Production caveats and edge cases

1. GitHub Pages legacy builds ignore _plugins/

GitHub Pages’ default branch deployment runs Jekyll in --safe mode, which disables all custom Ruby code under _plugins/. To run this hook in production, switch your Pages source to GitHub Actions and build _site explicitly in .github/workflows/pages-deploy.yml:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# .github/workflows/pages-deploy.yml (core build job)
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v7
        with:
          fetch-depth: 0

      - name: Setup Pages
        id: pages
        uses: actions/configure-pages@v6

      - name: Setup Ruby
        uses: ruby/setup-ruby@v1
        with:
          ruby-version: 3.4
          bundler-cache: true

      - name: Build site
        run: bundle exec jekyll b -d "_site${{ steps.pages.outputs.base_path }}" --config _config.yml,_config_prod.yml
        env:
          JEKYLL_ENV: "production"

Setting fetch-depth: 0 also ensures Git-based last_modified_at hooks can read full commit history during CI builds.

2. Guarding _drafts/ during local previews

Production builds ignore _drafts/, so this isn’t an issue in CI. However, when you run bundle exec jekyll serve --drafts locally, Jekyll includes drafts inside site.posts.docs. Because a draft’s relative_path starts with _drafts/ rather than _posts/, the naive sub(%r{^_posts/}, '') leaves "_drafts" in subdirs and injects _drafts as a category.

If you preview drafts locally often, add a guard at the top of the loop:

1
next unless post.relative_path.start_with?('_posts/')

3. Spaces in folder names and archive URL slugs

If a directory name contains a space—such as _posts/Home Server/Containers/—Chirpy displays Home Server in the UI, while jekyll-archives runs Jekyll::Utils.slugify to generate /categories/home-server/. Always reference the lowercase hyphenated slug rather than %20 in internal links so htmlproofer checks pass cleanly.

4. Avoid duplicate subcategory names across different parents

In Chirpy and jekyll-archives, each category name maps to a single flat URL (/categories/<slug>/). Don’t create the same subcategory name under two different parent folders (for example, _posts/Spring/Testing/ and _posts/Kotlin/Testing/), or both folders will collide into the same /categories/testing/ archive page.


Summary and checklist

Roughly 20 lines of Ruby in :site, :post_read keep your disk hierarchy and blog navigation permanently in sync without duplicating categories in Front Matter.

  • _plugins/category-folder-hook.rb registered on :site, :post_read (before generate)
  • GitHub Pages configured to deploy via GitHub Actions (not --safe mode)
  • categories removed from post Front Matter so folder paths remain the single source of truth
  • _drafts/ guard added if you use jekyll serve --drafts locally
  • Unique subcategory folder names verified across all parent directories

For the full list of Jekyll plugin hook events and execution order, see the official documentation:

Using hooks, your plugin can exercise fine-grained control over various aspects of the build process. If your plugin defines any hooks, Jekyll will call them at pre-defined points.
This post is licensed under CC BY 4.0 by the author.