WordPress

把 WordPress 当作 headless CMS,把整个站点抓下来:分页遍历 /wp-json/wp/v2/posts,为每个 slug 生成一个 HTML 文件,并在多次构建之间缓存 API 响应。

你会得到什么

项目结构

my-site/
  sitelo.config.js
  src/
    lib/
      wordpress.js       # WP REST 辅助函数(分页抓取)
    index.ht.js          # 首页 —— 列出最新文章
    blog/
      index.ht.js        # /blog —— 完整归档
      [slug].ht.js       # /blog/:slug —— 每一篇文章
    css/
      styles.css
export default {
  site: 'https://example.com',
  // 成千上万个页面?调高并发
  renderConcurrency: 16,
  renderBatchSize: 128,
}

1. 指向你的 WordPress 站点

现代 WordPress 默认开启 REST API。可以在 https://你的站点.com/wp-json/wp/v2/posts 确认。

在环境变量里设置 WP_URL(试验阶段直接写死也行):

WP_URL=https://your-wordpress-site.com

2. 共用的 WordPress 辅助函数

getAllPosts() 读取 X-WP-TotalPages 并逐页遍历(WordPress 把 per_page 限制在 100)。收集 slug 时跳过 _embed —— 只在取单篇文章时才请求内嵌内容。

import { fetchWithCache } from 'sitelo'

const WP_URL = process.env.WP_URL ?? 'https://your-wordpress-site.com'
const PER_PAGE = 100 // /wp/v2/posts 的 WP 上限

async function wpFetch(path, query = {}) {
  const url = new URL(`/wp-json/wp/v2${path}`, WP_URL)
  for (const [key, value] of Object.entries(query)) {
    if (value != null) url.searchParams.set(key, String(value))
  }

  const res = await fetchWithCache(url, undefined, {
    maxAge: 3600,
    cache: 'auto',
  })

  if (!res.ok) {
    throw new Error(`WordPress ${res.status}: ${url}`)
  }

  return {
    data: await res.json(),
    totalPages: Number(res.headers.get('X-WP-TotalPages') ?? 1),
    total: Number(res.headers.get('X-WP-Total') ?? 0),
  }
}

export async function getPosts({ page = 1, perPage = 20, embed = true } = {}) {
  const { data } = await wpFetch('/posts', {
    page,
    per_page: perPage,
    _embed: embed ? '1' : undefined,
  })
  return data
}

/** 逐页遍历 /posts,直到把整个站点抓完。 */
export async function getAllPosts({
  perPage = PER_PAGE,
  embed = false,
  onPage,
} = {}) {
  const first = await wpFetch('/posts', {
    page: 1,
    per_page: perPage,
    _embed: embed ? '1' : undefined,
  })

  const posts = [...first.data]
  onPage?.(1, first.totalPages, posts.length)

  for (let page = 2; page <= first.totalPages; page += 1) {
    const next = await wpFetch('/posts', {
      page,
      per_page: perPage,
      _embed: embed ? '1' : undefined,
    })
    posts.push(...next.data)
    onPage?.(page, first.totalPages, posts.length)
  }

  return posts
}

export async function getPostBySlug(slug) {
  const { data } = await wpFetch('/posts', {
    slug,
    _embed: '1',
  })
  return data[0] ?? null
}

export function postPath(post) {
  return `/blog/${post.slug}`
}

export function featuredImage(post) {
  return post._embedded?.['wp:featuredmedia']?.[0]?.source_url
}

3. 首页

import { html, head, title, link, body, h1, ul, li, a, p } from 'javascript-to-html'
import { getPosts, postPath } from './lib/wordpress.js'

export async function data() {
  const posts = await getPosts({ perPage: 5 })
  return { posts }
}

export default ({ data }) =>
  html({ lang: 'zh' },
    head(
      title('我的网站'),
      link({ rel: 'stylesheet', href: '/styles.css' }),
    ),
    body(
      h1('博客最新'),
      ul(
        ...data.posts.map((post) =>
          li(a({ href: postPath(post) }, post.title.rendered)),
        ),
      ),
      p(a({ href: '/blog' }, '全部文章')),
    ),
  )

4. 博客索引

使用 getAllPosts(),这样归档就不会被限制在 50–100 条。

import { html, head, title, link, body, h1, ul, li, a, time } from 'javascript-to-html'
import { getAllPosts, postPath } from '../lib/wordpress.js'

export async function data() {
  // 完整归档 —— 分页遍历整个 WP 站点
  const posts = await getAllPosts({ embed: false })
  return { posts }
}

export default ({ data }) =>
  html({ lang: 'zh' },
    head(
      title('博客'),
      link({ rel: 'stylesheet', href: '/styles.css' }),
    ),
    body(
      h1(`博客 (${data.posts.length})`),
      ul(
        ...data.posts.map((post) =>
          li(
            a({ href: postPath(post) }, post.title.rendered),
            time(post.date.slice(0, 10)),
          ),
        ),
      ),
    ),
  )

5. 把每篇文章都变成静态页面

generateStaticParams 必须返回你希望出现在 dist/ 里的每一个 slug。请在这里对 API 分页 —— 不要只调用一次 getPosts({ perPage: 100 }) 就收工。

import {
  html, head, title, link, body, article, p, a, h1, time, img, div,
} from 'javascript-to-html'
import {
  getAllPosts,
  getPostBySlug,
  featuredImage,
} from '../lib/wordpress.js'

export async function generateStaticParams() {
  const ripStarted = performance.now()
  console.log(
    `[wordpress] 正在抓取文章… (${process.uptime().toFixed(1)}s 自启动以来)`,
  )

  // 抓取每一篇已发布的文章(几千篇也没问题 —— 每次请求 100 篇)
  const posts = await getAllPosts({
    embed: false, // 只要 slug;为了速度跳过 _embed
    onPage: (page, totalPages, count) => {
      console.log(`[wordpress] 第 ${page}/${totalPages} (${count} 篇文章)`)
    },
  })

  const ripSeconds = ((performance.now() - ripStarted) / 1000).toFixed(1)
  console.log(
    `[wordpress] 已抓取 ${posts.length} 篇文章 耗时 ${ripSeconds}s` +
      ` (${process.uptime().toFixed(1)}s 自启动以来)`,
  )

  return posts.map((post) => ({ slug: post.slug }))
}

export async function data({ params }) {
  const post = await getPostBySlug(params.slug)
  if (!post) throw new Error(`找不到文章: ${params.slug}`)
  return { post }
}

export default ({ data }) => {
  const { post } = data
  const image = featuredImage(post)

  return html({ lang: 'zh' },
    head(
      title(post.title.rendered),
      link({ rel: 'stylesheet', href: '/styles.css' }),
    ),
    body(
      article(
        p(a({ href: '/blog' }, '← 博客')),
        h1(post.title.rendered),
        time(post.date.slice(0, 10)),
        image ? img({ src: image, alt: '' }) : '',
        div({ class: 'content' }, post.content.rendered),
      ),
    ),
  )
}

6. 构建

WP_URL=https://your-wordpress-site.com sitelo build

首次构建会完整走一遍 WordPress,并填满 fetch 缓存。后续构建会复用缓存的列表和详情响应(cache: 'auto' → 生产环境用文件系统),直到 maxAge 过期。如果要渲染数千个文章页,请在 sitelo.config.js 中调高 renderConcurrency

说明

来自 WordPress 的 HTML

title.renderedcontent.rendered 是 WP 给出的 HTML 字符串。可以像上面那样原样放进模板;如果你并不完全信任这个 CMS,就先做净化。

非公开内容

公开的 REST 路由只会暴露已发布的文章。若要取草稿或使用自定义鉴权,请在 fetchWithCache 的第二个参数里传入请求头(就是标准的 fetch init),并使用稳定的 cacheKey

数据加载文档 · 路由文档