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.
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-chirpy7.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
Springin one file andspringin 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.
| Approach | File browsing ergonomics | Typo & drift risk | Custom plugin required |
|---|---|---|---|
Manual Front Matter categories | Fair | High (dual maintenance) | No |
Top-level folders (cat/_posts/) | Poor (scattered across repo) | Low | No |
_posts/ subfolders + Ruby hook | High (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:
post.relative_path.sub(%r{^_posts/}, '')strips the leading_posts/prefix (if you also run a multilingual build withcollections_dir: en, strip%r{^(?:en/)?_posts/}instead—see Building a bilingual Jekyll Chirpy blog with dual builds)..split('/')[0...-1]splits the path segments and drops the final filename, leaving only the directory chain.- 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: 0also ensures Git-basedlast_modified_athooks 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.rbregistered on:site, :post_read(beforegenerate)- GitHub Pages configured to deploy via GitHub Actions (not
--safemode) categoriesremoved from post Front Matter so folder paths remain the single source of truth_drafts/guard added if you usejekyll serve --draftslocally- 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: