WordPress Block Theme
WordPress Block Theme เป็นรูปแบบ Theme ใหม่ที่ใช้ Full Site Editing (FSE) ทุกส่วนของเว็บแก้ไขผ่าน Block Editor รวมถึง Header, Footer, Sidebar และ Templates ใช้ theme.json เป็นศูนย์กลาง Configuration แทน PHP Functions
เมื่อรวมกับ Edge Deployment ได้เว็บที่ทั้งยืดหยุ่นในการแก้ไข และเร็วสำหรับผู้ใช้ทั่วโลก CDN Cache Static Assets, Edge Functions จัดการ Dynamic Content, Image Optimization ลด Bandwidth
Block Theme Development
# === WordPress Block Theme Structure ===
# โครงสร้างไฟล์ Block Theme
# my-block-theme/
# ├── style.css # Theme Header
# ├── theme.json # Global Styles & Settings
# ├── functions.php # Optional PHP Functions
# ├── templates/ # Page Templates (HTML)
# │ ├── index.html # Default Template
# │ ├── single.html # Single Post
# │ ├── page.html # Page Template
# │ ├── archive.html # Archive
# │ ├── 404.html # 404 Page
# │ └── search.html # Search Results
# ├── parts/ # Template Parts (HTML)
# │ ├── header.html # Header
# │ ├── footer.html # Footer
# │ └── sidebar.html # Sidebar
# ├── patterns/ # Block Patterns (PHP)
# │ ├── hero.php # Hero Section
# │ └── cta.php # Call to Action
# └── assets/
# ├── css/
# ├── js/
# └── images/
# === style.css (Theme Header) ===
cat > style.css << 'CSSEOF'
/*
Theme Name: My Block Theme
Theme URI: https://example.com/theme
Author: SiamCafe
Author URI: https://siamcafe.net
Description: Modern Block Theme for Edge Deployment
Version: 1.0.0
Requires at least: 6.4
Tested up to: 6.5
Requires PHP: 8.0
License: GPL-2.0-or-later
Text Domain: my-block-theme
*/
CSSEOF
# === theme.json (Global Styles & Settings) ===
cat > theme.json << 'JSONEOF'
{
"$schema": "https://schemas.wp.org/wp/6.5/theme.json",
"version": 2,
"settings": {
"appearanceTools": true,
"color": {
"palette": [
{"slug": "primary", "color": "#0D9373", "name": "Primary"},
{"slug": "secondary", "color": "#1a1a2e", "name": "Secondary"},
{"slug": "accent", "color": "var(--c-primary)", "name": "Accent"},
{"slug": "background", "color": "#ffffff", "name": "Background"},
{"slug": "foreground", "color": "#1a1a2e", "name": "Foreground"}
]
},
"typography": {
"fontFamilies": [
{
"fontFamily": "Inter, sans-serif",
"slug": "inter",
"name": "Inter",
"fontFace": [
{"fontFamily": "Inter", "fontWeight": "400", "fontStyle": "normal",
"src": ["file:./assets/fonts/inter-regular.woff2"]},
{"fontFamily": "Inter", "fontWeight": "700", "fontStyle": "normal",
"src": ["file:./assets/fonts/inter-bold.woff2"]}
]
}
],
"fontSizes": [
{"slug": "small", "size": "0.875rem", "name": "Small"},
{"slug": "medium", "size": "1rem", "name": "Medium"},
{"slug": "large", "size": "1.5rem", "name": "Large"},
{"slug": "x-large", "size": "2.25rem", "name": "Extra Large"}
]
},
"layout": {
"contentSize": "800px",
"wideSize": "1200px"
},
"spacing": {
"units": ["px", "rem", "em", "%", "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)",
"lineHeight": "1.6"
},
"elements": {
"link": {
"color": {"text": "var(--wp--preset--color--primary)"},
":hover": {"color": {"text": "var(--wp--preset--color--accent)"}}
},
"h1": {"typography": {"fontSize": "var(--wp--preset--font-size--x-large)"}},
"h2": {"typography": {"fontSize": "var(--wp--preset--font-size--large)"}}
}
},
"templateParts": [
{"name": "header", "title": "Header", "area": "header"},
{"name": "footer", "title": "Footer", "area": "footer"}
]
}
JSONEOF
echo "Block Theme structure created"
Edge Deployment Configuration
# === Edge Deployment สำหรับ WordPress ===
# 1. Cloudflare Configuration (wrangler.toml)
# name = "wp-edge"
# main = "src/worker.js"
# compatibility_date = "2024-01-01"
#
# [vars]
# ORIGIN = "https://api.example.com"
#
# [[r2_buckets]]
# binding = "ASSETS"
# bucket_name = "wp-assets"
# 2. Cloudflare Worker — Edge Cache สำหรับ WordPress
# src/worker.js
# export default {
# async fetch(request, env) {
# const url = new URL(request.url);
#
# // Static Assets -> R2/Cache (1 year)
# if (url.pathname.match(/\.(css|js|png|jpg|webp|woff2|svg)$/)) {
# const cache = caches.default;
# let response = await cache.match(request);
# if (!response) {
# response = await fetch(request);
# response = new Response(response.body, response);
# response.headers.set('Cache-Control', 'public, max-age=31536000, immutable');
# await cache.put(request, response.clone());
# }
# return response;
# }
#
# // HTML Pages -> Edge Cache (60s)
# if (request.method === 'GET' && !url.pathname.startsWith('/wp-admin')) {
# const cache = caches.default;
# let response = await cache.match(request);
# if (!response) {
# response = await fetch(env.ORIGIN + url.pathname);
# response = new Response(response.body, response);
# response.headers.set('Cache-Control', 'public, s-maxage=60, stale-while-revalidate=300');
# await cache.put(request, response.clone());
# }
# return response;
# }
#
# // Dynamic -> Origin
# return fetch(env.ORIGIN + url.pathname + url.search, request);
# }
# };
# === Nginx Edge Cache Configuration ===
# /etc/nginx/conf.d/edge-cache.conf
proxy_cache_path /var/cache/nginx/wp levels=1:2
keys_zone=wp_edge:100m max_size=10g inactive=7d
use_temp_path=off;
map $request_uri $skip_cache {
default 0;
~*/wp-admin 1;
~*/wp-login 1;
~*/wp-json 1;
~*preview=true 1;
}
server {
listen 443 ssl http2;
server_name www.example.com;
# SSL
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# Static Assets — Long Cache
location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg|woff2|webp|avif)$ {
proxy_pass http://wordpress;
proxy_cache wp_edge;
proxy_cache_valid 200 365d;
add_header Cache-Control "public, max-age=31536000, immutable";
add_header X-Cache-Status $upstream_cache_status;
}
# HTML Pages — Short Cache + Stale
location / {
proxy_pass http://wordpress;
proxy_cache wp_edge;
proxy_cache_valid 200 60s;
proxy_cache_bypass $skip_cache;
proxy_no_cache $skip_cache;
proxy_cache_use_stale error timeout updating http_500 http_502;
add_header Cache-Control "public, s-maxage=60, stale-while-revalidate=300";
add_header X-Cache-Status $upstream_cache_status;
}
# wp-admin — No Cache
location /wp-admin {
proxy_pass http://wordpress;
add_header Cache-Control "no-store, no-cache, must-revalidate";
}
}
Performance Optimization Script
# wp_edge_optimize.py — Optimize WordPress สำหรับ Edge Deployment
import requests
import json
import time
from datetime import datetime
class WPEdgeOptimizer:
"""ตรวจสอบและ Optimize WordPress สำหรับ Edge"""
def __init__(self, site_url):
self.site_url = site_url.rstrip("/")
self.session = requests.Session()
def check_cache_headers(self, path="/"):
"""ตรวจสอบ Cache Headers"""
url = f"{self.site_url}{path}"
resp = self.session.get(url, allow_redirects=True)
headers = {
"cache-control": resp.headers.get("Cache-Control", ""),
"x-cache": resp.headers.get("X-Cache-Status", ""),
"cf-cache-status": resp.headers.get("CF-Cache-Status", ""),
"age": resp.headers.get("Age", ""),
"content-encoding": resp.headers.get("Content-Encoding", ""),
}
return {"url": url, "status": resp.status_code, "headers": headers}
def measure_ttfb(self, path="/", n=5):
"""วัด Time to First Byte"""
url = f"{self.site_url}{path}"
ttfbs = []
for _ in range(n):
start = time.perf_counter()
resp = self.session.get(url)
ttfb = (time.perf_counter() - start) * 1000
ttfbs.append(ttfb)
avg = sum(ttfbs) / len(ttfbs)
p50 = sorted(ttfbs)[len(ttfbs) // 2]
best = min(ttfbs)
return {"avg_ms": round(avg), "p50_ms": round(p50),
"best_ms": round(best)}
def check_assets(self):
"""ตรวจสอบ Static Assets"""
paths = [
"/wp-content/themes/my-theme/style.css",
"/wp-includes/js/jquery/jquery.min.js",
]
results = []
for path in paths:
info = self.check_cache_headers(path)
results.append(info)
return results
def full_audit(self):
"""Full Performance Audit"""
print(f"\n{'='*55}")
print(f"WordPress Edge Audit — {self.site_url}")
print(f"{'='*55}")
# TTFB
print(f"\nTTFB (Time to First Byte):")
ttfb = self.measure_ttfb("/")
print(f" Avg: {ttfb['avg_ms']}ms | P50: {ttfb['p50_ms']}ms | "
f"Best: {ttfb['best_ms']}ms")
grade = "A" if ttfb["avg_ms"] < 200 else \
"B" if ttfb["avg_ms"] < 500 else \
"C" if ttfb["avg_ms"] < 1000 else "F"
print(f" Grade: {grade}")
# Cache Headers
print(f"\nCache Headers (HTML):")
html = self.check_cache_headers("/")
for key, val in html["headers"].items():
if val:
print(f" {key}: {val}")
print(f"\nCache Headers (CSS):")
css = self.check_cache_headers("/wp-content/themes/my-theme/style.css")
for key, val in css["headers"].items():
if val:
print(f" {key}: {val}")
# Recommendations
print(f"\nRecommendations:")
if ttfb["avg_ms"] > 500:
print(f" - Enable Edge Caching (CDN)")
if "immutable" not in html["headers"].get("cache-control", ""):
print(f" - Add 'immutable' to static asset cache headers")
if not html["headers"].get("content-encoding"):
print(f" - Enable gzip/brotli compression")
# optimizer = WPEdgeOptimizer("https://www.example.com")
# optimizer.full_audit()
Best Practices
- theme.json: ใช้ theme.json เป็นศูนย์กลาง Configuration แทน PHP Functions
- Local Fonts: Host Fonts เองแทน Google Fonts ลด External Requests
- Edge Cache: ใช้ CDN Cache HTML (short TTL) และ Assets (long TTL + immutable)
- Image Optimization: ใช้ WebP/AVIF Format, Lazy Load, Responsive Images
- Stale-while-revalidate: ส่ง Cache เก่าให้ผู้ใช้ขณะ Fetch ข้อมูลใหม่จาก Origin
- Purge Strategy: Purge Cache เมื่อ Publish/Update Post ใช้ Webhook หรือ Plugin
WordPress Block Theme คืออะไร
Theme รูปแบบใหม่ใช้ Full Site Editing ทุกส่วนแก้ไขผ่าน Block Editor ใช้ theme.json กำหนด Styles Settings ไม่ต้องเขียน PHP Templates ใช้ HTML Templates แทน
Edge Deployment คืออะไร
Deploy เว็บไปยัง Edge Servers ใกล้ผู้ใช้ทั่วโลก ลด Latency เพิ่มความเร็ว เช่น Cloudflare Workers Vercel Edge AWS CloudFront Fastly ทำให้เว็บโหลดเร็วทุกประเทศ
Block Theme ดีกว่า Classic Theme อย่างไร
แก้ไขทุกส่วนผ่าน Block Editor ไม่ต้องเขียน Code theme.json จัดการ Styles ง่าย Global Styles เปลี่ยน Design ทั้งเว็บจากที่เดียว Performance ดีกว่า Load เฉพาะ Blocks ที่ใช้
วิธี Optimize WordPress สำหรับ Edge ทำอย่างไร
CDN Cache Static Assets ตั้ง Cache Headers เหมาะสม (immutable สำหรับ Assets short TTL สำหรับ HTML) Edge Functions สำหรับ Dynamic Content Optimize Images WebP/AVIF Lazy Load Minimize CSS/JS
สรุป
WordPress Block Theme ร่วมกับ Edge Deployment ให้เว็บที่ยืดหยุ่นและเร็ว ใช้ theme.json เป็นศูนย์กลาง Full Site Editing แก้ไขทุกส่วน Deploy ไปยัง Edge ด้วย CDN Cache Assets แบบ Immutable HTML แบบ Short TTL + Stale-while-revalidate ใช้ Edge Functions สำหรับ Dynamic Content Optimize Images ด้วย WebP/AVIF
