WordPress

Trata WordPress como un CMS headless y descarga el sitio entero: pagina por /wp-json/wp/v2/posts, genera un archivo HTML por slug y cachea las respuestas de la API entre compilaciones.

Qué obtienes

Estructura del proyecto

my-site/
  sitelo.config.js
  src/
    lib/
      wordpress.js       # ayudantes de la REST de WP (descarga paginada)
    index.ht.js          # inicio — lista las entradas más recientes
    blog/
      index.ht.js        # /blog — archivo completo
      [slug].ht.js       # /blog/:slug — todas las entradas
    css/
      styles.css
export default {
  site: 'https://example.com',
  // ¿miles de páginas? sube la concurrencia
  renderConcurrency: 16,
  renderBatchSize: 128,
}

1. Apunta a tu sitio WordPress

La API REST viene activada por defecto en las versiones modernas de WordPress. Compruébalo en https://tu-sitio.com/wp-json/wp/v2/posts.

Define WP_URL en el entorno (o escríbelo directamente mientras experimentas):

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

2. Ayudantes compartidos de WordPress

getAllPosts() lee X-WP-TotalPages y recorre todas las páginas (WordPress limita per_page a 100). Omite _embed mientras recoges slugs — pide los embeds solo para cada entrada concreta.

import { fetchWithCache } from 'sitelo'

const WP_URL = process.env.WP_URL ?? 'https://your-wordpress-site.com'
const PER_PAGE = 100 // máximo de WP para /wp/v2/posts

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
}

/** Recorre todas las páginas de /posts hasta descargar el sitio entero. */
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. Portada

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: 'es' },
    head(
      title('Mi sitio'),
      link({ rel: 'stylesheet', href: '/styles.css' }),
    ),
    body(
      h1('Lo último del blog'),
      ul(
        ...data.posts.map((post) =>
          li(a({ href: postPath(post) }, post.title.rendered)),
        ),
      ),
      p(a({ href: '/blog' }, 'Todas las entradas')),
    ),
  )

4. Índice del blog

Usa getAllPosts() para que el archivo no se quede limitado a 50–100 elementos.

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() {
  // Archivo completo — pagina por todo el sitio de WP
  const posts = await getAllPosts({ embed: false })
  return { posts }
}

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

5. Convierte todas las entradas en páginas estáticas

generateStaticParams debe devolver todos los slugs que quieras en dist/. Pagina la API aquí — no llames a getPosts({ perPage: 100 }) una sola vez y te quedes ahí.

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] descargando entradas… (${process.uptime().toFixed(1)}s desde el inicio)`,
  )

  // Descarga todas las entradas publicadas (miles no son problema — 100 por petición)
  const posts = await getAllPosts({
    embed: false, // solo slugs; omite _embed por velocidad
    onPage: (page, totalPages, count) => {
      console.log(`[wordpress] página ${page}/${totalPages} (${count} entradas)`)
    },
  })

  const ripSeconds = ((performance.now() - ripStarted) / 1000).toFixed(1)
  console.log(
    `[wordpress] descargadas ${posts.length} entradas en ${ripSeconds}s` +
      ` (${process.uptime().toFixed(1)}s desde el inicio)`,
  )

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

export async function data({ params }) {
  const post = await getPostBySlug(params.slug)
  if (!post) throw new Error(`Entrada no encontrada: ${params.slug}`)
  return { post }
}

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

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

6. Compilar

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

La primera compilación pasa una vez por WordPress y llena la caché de fetch. Las siguientes reutilizan las respuestas cacheadas de listado y detalle (cache: 'auto' → sistema de archivos en producción) hasta que expire maxAge. Sube renderConcurrency en sitelo.config.js si vas a renderizar miles de páginas de entradas.

Notas

HTML procedente de WordPress

title.rendered y content.rendered son cadenas HTML que vienen de WP. Colócalas en tu plantilla tal cual (como arriba), o sanitízalas si no te fías del todo del CMS.

Contenido privado

Las rutas REST públicas solo exponen entradas publicadas. Para borradores o autenticación propia, pasa cabeceras en el segundo argumento de fetchWithCache (el init estándar de fetch) y usa un cacheKey estable.

Documentación de carga de datos · Documentación de rutas