SiamCafe · Blog
WordPress Block Theme Automation Script — สร้าง
บทความ

WordPress Block Theme Automation Script — สร้าง

เผยแพร่ 28 พฤษภาคม 2569

WordPress Block Theme Automation

WordPress Block Theme Automation Script — สร้าง

WordPress Block Theme Automation Script FSE Full Site Editing theme.json Templates Parts Patterns Build Deploy CI/CD Production

ComponentFilePurposeFormat
Configtheme.jsonSettings Styles Layout Colors TypographyJSON
Templatestemplates/*.htmlPage Layout (index single archive)HTML (Block Markup)
Partsparts/*.htmlReusable Parts (header footer)HTML (Block Markup)
Patternspatterns/*.phpBlock Patterns (Hero CTA Grid)PHP (with Block Markup)
Stylesstyles/*.jsonStyle Variations (Dark Light)JSON
Infostyle.cssTheme Name Version AuthorCSS Header

Theme Generator Script

# === WordPress Block Theme Generator ===

# #!/usr/bin/env python3
# """Generate WordPress Block Theme structure automatically."""
# import os, json, zipfile

# THEME_NAME = "my-block-theme"
# THEME_DISPLAY = "My Block Theme"
# THEME_VERSION = "1.0.0"
# THEME_AUTHOR = "SiamCafe"
#
# # Directory structure
# dirs = ["templates", "parts", "styles", "patterns", "assets/fonts", "assets/images"]
# for d in dirs:
#     os.makedirs(f"{THEME_NAME}/{d}", exist_ok=True)

from dataclasses import dataclass

@dataclass
class ThemeFile:
    path: str
    content_type: str
    description: str
    required: bool

theme_files = [
    ThemeFile("style.css",
        "CSS Header (Theme metadata)",
        "Theme Name Version Author Description License",
        True),
    ThemeFile("theme.json",
        "JSON (Settings + Styles)",
        "Colors Typography Layout Spacing Block Settings",
        True),
    ThemeFile("templates/index.html",
        "HTML (Block Markup)",
        "Main Template Query Loop Post List",
        True),
    ThemeFile("templates/single.html",
        "HTML (Block Markup)",
        "Single Post Template Content Comments",
        True),
    ThemeFile("templates/page.html",
        "HTML (Block Markup)",
        "Page Template Content",
        True),
    ThemeFile("templates/archive.html",
        "HTML (Block Markup)",
        "Archive Template Category Tag Date",
        False),
    ThemeFile("templates/404.html",
        "HTML (Block Markup)",
        "404 Not Found Page",
        False),
    ThemeFile("parts/header.html",
        "HTML (Block Markup)",
        "Site Header Navigation Logo",
        True),
    ThemeFile("parts/footer.html",
        "HTML (Block Markup)",
        "Site Footer Copyright Links",
        True),
    ThemeFile("patterns/hero.php",
        "PHP (Block Pattern)",
        "Hero Banner Section",
        False),
    ThemeFile("styles/dark.json",
        "JSON (Style Variation)",
        "Dark Mode Color Palette",
        False),
]

print("=== Theme Files ===")
for f in theme_files:
    req = "Required" if f.required else "Optional"
    print(f"  [{f.path}] ({req})")
    print(f"    Type: {f.content_type}")
    print(f"    Desc: {f.description}")

theme.json Configuration

WordPress Block Theme Automation Script — สร้าง
# === theme.json Generator ===

# theme_json = {
#     "$schema": "https://schemas.wp.org/trunk/theme.json",
#     "version": 2,
#     "settings": {
#         "color": {
#             "palette": [
#                 {"slug": "primary", "color": "#1e40af", "name": "Primary"},
#                 {"slug": "secondary", "color": "#7c3aed", "name": "Secondary"},
#                 {"slug": "accent", "color": "#f59e0b", "name": "Accent"},
#                 {"slug": "background", "color": "#ffffff", "name": "Background"},
#                 {"slug": "foreground", "color": "#1f2937", "name": "Foreground"},
#             ]
#         },
#         "typography": {
#             "fontFamilies": [
#                 {"fontFamily": "Inter, sans-serif", "slug": "inter", "name": "Inter"},
#                 {"fontFamily": "JetBrains Mono, monospace", "slug": "mono", "name": "Mono"},
#             ],
#             "fontSizes": [
#                 {"slug": "small", "size": "0.875rem", "name": "Small"},
#                 {"slug": "medium", "size": "1rem", "name": "Medium"},
#                 {"slug": "large", "size": "1.25rem", "name": "Large"},
#                 {"slug": "x-large", "size": "2rem", "name": "XL"},
#             ]
#         },
#         "layout": {"contentSize": "800px", "wideSize": "1200px"},
#         "spacing": {"units": ["px", "rem", "%", "vh", "vw"]},
#     },
#     "styles": {
#         "color": {"background": "var(--wp--preset--color--background)",
#                   "text": "var(--wp--preset--color--foreground)"},
#         "typography": {"fontFamily": "var(--wp--preset--font-family--inter)",
#                        "fontSize": "var(--wp--preset--font-size--medium)"},
#         "elements": {
#             "h1": {"typography": {"fontSize": "2.5rem", "fontWeight": "700"}},
#             "h2": {"typography": {"fontSize": "2rem", "fontWeight": "600"}},
#             "link": {"color": {"text": "var(--wp--preset--color--primary)"}},
#         },
#     },
# }
# with open(f"{THEME_NAME}/theme.json", "w") as f:
#     json.dump(theme_json, f, indent=2)

@dataclass
class ThemeJsonSection:
    section: str
    key_settings: str
    example: str
    tip: str

sections = [
    ThemeJsonSection("settings.color.palette",
        "Custom Color Palette สำหรับ Editor",
        "primary secondary accent background foreground",
        "ใช้ 5-8 สี ตั้งชื่อ slug ชัดเจน"),
    ThemeJsonSection("settings.typography",
        "Font Families Font Sizes",
        "Inter sans-serif | small medium large x-large",
        "ใช้ Local Fonts (assets/fonts) ลด External Request"),
    ThemeJsonSection("settings.layout",
        "Content Width Wide Width",
        "contentSize: 800px wideSize: 1200px",
        "ไม่เกิน 1400px สำหรับ Wide Content"),
    ThemeJsonSection("styles.elements",
        "Default Styles สำหรับ HTML Elements",
        "h1-h6 p a button",
        "ตั้ง Base Style ที่นี่ ไม่ต้องเขียน CSS"),
    ThemeJsonSection("styles.blocks",
        "Default Styles สำหรับ Specific Blocks",
        "core/button core/heading core/paragraph",
        "Override Block Default Styles ได้ละเอียด"),
]

print("=== theme.json Sections ===")
for s in sections:
    print(f"  [{s.section}]")
    print(f"    Settings: {s.key_settings}")
    print(f"    Example: {s.example}")
    print(f"    Tip: {s.tip}")

Build & Deploy Pipeline

# === CI/CD Pipeline ===

# GitHub Actions (.github/workflows/deploy.yml)
# name: Deploy Theme
# on:
#   push:
#     tags: ['v*']
# jobs:
#   build:
#     runs-on: ubuntu-latest
#     steps:
#       - uses: actions/checkout@v4
#       - name: Validate theme.json
#         run: |
#           python -c "import json; json.load(open('theme.json'))"
#       - name: Create ZIP
#         run: |
#           zip -r my-block-theme.zip . -x '.git/*' '.github/*' 'node_modules/*'
#       - name: Deploy to WordPress
#         run: |
#           wp theme install my-block-theme.zip --activate \
#             --ssh=user@server:/var/www/html

@dataclass
class PipelineStep:
    step: str
    tool: str
    command: str
    purpose: str

pipeline = [
    PipelineStep("Lint",
        "theme-check / jsonlint",
        "npx jsonlint theme.json && wp theme check",
        "ตรวจ theme.json ถูกต้อง Theme มาตรฐาน"),
    PipelineStep("Validate Templates",
        "Custom Script",
        "python validate_templates.py templates/ parts/",
        "ตรวจ Block Markup ถูกต้อง ไม่มี Syntax Error"),
    PipelineStep("Build ZIP",
        "zip",
        "zip -r theme.zip . -x '.git/*' 'node_modules/*'",
        "สร้าง ZIP พร้อม Install"),
    PipelineStep("Deploy Staging",
        "WP-CLI + SSH",
        "wp theme install theme.zip --activate --ssh=staging",
        "ทดสอบบน Staging ก่อน Production"),
    PipelineStep("Smoke Test",
        "curl / Playwright",
        "curl -s https://staging.example.com | grep 'theme-name'",
        "ตรวจ Theme ทำงานบน Staging"),
    PipelineStep("Deploy Production",
        "WP-CLI + SSH",
        "wp theme install theme.zip --activate --ssh=production",
        "Deploy Production หลัง Staging ผ่าน"),
]

print("=== Pipeline Steps ===")
for p in pipeline:
    print(f"  [{p.step}] {p.tool}")
    print(f"    Command: {p.command}")
    print(f"    Purpose: {p.purpose}")

เคล็ดลับ

  • theme.json: ใช้ theme.json ควบคุม Style ไม่เขียน CSS มาก
  • Patterns: สร้าง Block Patterns ใช้ซ้ำได้ทุกหน้า
  • Local Fonts: เก็บ Font ใน assets/fonts ลด External Request
  • Variations: สร้าง Style Variations สำหรับ Dark/Light Mode
  • WP-CLI: ใช้ WP-CLI สำหรับ Deploy อัตโนมัติ

Block Theme คืออะไร

WordPress FSE Full Site Editing Block Editor HTML Templates theme.json Parts Patterns Styles Visual Editing ไม่ต้อง PHP มาก