WordPress
Na tej stronie
Potraktuj WordPressa jak headless CMS i pobierz całą witrynę: przejdź stronicowaniem przez /wp-json/wp/v2/posts, wygeneruj jeden plik HTML na slug i buforuj odpowiedzi API między buildami.
Co dostajesz
- Stronę główną z listą najnowszych wpisów
/blog— pełne archiwum wszystkich wpisów/blog/[slug]— jedną statyczną stronę HTML na wpis (działa przy tysiącach wpisów)fetchWithCache, żeby kolejne buildy używały odpowiedzi WP zamiast pobierać wszystko od nowa
Układ projektu
my-site/
sitelo.config.js
src/
lib/
wordpress.js # pomocniki REST WP (stronicowane pobieranie)
index.ht.js # strona główna — lista najnowszych wpisów
blog/
index.ht.js # /blog — pełne archiwum
[slug].ht.js # /blog/:slug — każdy wpis
css/
styles.cssexport default {
site: 'https://example.com',
// tysiące stron? zwiększ współbieżność
renderConcurrency: 16,
renderBatchSize: 128,
}1. Wskaż swoją witrynę WordPress
W nowoczesnym WordPressie REST API jest domyślnie włączone. Sprawdź to pod https://your-site.com/wp-json/wp/v2/posts.
Ustaw WP_URL w środowisku (albo wpisz na sztywno, póki eksperymentujesz):
WP_URL=https://your-wordpress-site.com2. Wspólne pomocniki WordPressa
getAllPosts() czyta X-WP-TotalPages i przechodzi każdą stronę (WordPress ogranicza per_page do 100). Przy zbieraniu slugów pomiń _embed — osadzenia pobieraj tylko dla pojedynczych wpisów.
import { fetchWithCache } from 'sitelo'
const WP_URL = process.env.WP_URL ?? 'https://your-wordpress-site.com'
const PER_PAGE = 100 // maksimum WP dla /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
}
/** Przejdź każdą stronę /posts, aż cała witryna zostanie pobrana. */
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. Strona główna
import { getPosts, postPath } from './lib/wordpress.js'
export async function data() {
const posts = await getPosts({ perPage: 5 })
return { posts }
}
export default ({ data }) => `
<html lang="pl">
<head>
<title>Moja strona</title>
<link rel="stylesheet" href="/css/styles.css">
</head>
<body>
<h1>Najnowsze z bloga</h1>
<ul>
${data.posts
.map(
(post) => `
<li>
<a href="${postPath(post)}">${post.title.rendered}</a>
</li>`,
)
.join('')}
</ul>
<p><a href="/blog">Wszystkie wpisy</a></p>
</body>
</html>
`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: 'pl' },
head(
title('Moja strona'),
link({ rel: 'stylesheet', href: '/styles.css' }),
),
body(
h1('Najnowsze z bloga'),
ul(
...data.posts.map((post) =>
li(a({ href: postPath(post) }, post.title.rendered)),
),
),
p(a({ href: '/blog' }, 'Wszystkie wpisy')),
),
)import { getPosts, postPath } from './lib/wordpress.js'
export async function data() {
const posts = await getPosts({ perPage: 5 })
return { posts }
}
export default function Home({ data }) {
return (
<html lang="pl">
<head>
<title>Moja strona</title>
<link rel="stylesheet" href="/css/styles.css" />
</head>
<body>
<h1>Najnowsze z bloga</h1>
<ul>
{data.posts.map((post) => (
<li key={post.slug}>
<a href={postPath(post)}>{post.title.rendered}</a>
</li>
))}
</ul>
<p><a href="/blog">Wszystkie wpisy</a></p>
</body>
</html>
)
}4. Indeks bloga
Użyj getAllPosts(), żeby archiwum nie zatrzymało się na 50–100 pozycjach.
import { getAllPosts, postPath } from '../lib/wordpress.js'
export async function data() {
// Pełne archiwum — przejdź stronicowaniem przez całą witrynę WP
const posts = await getAllPosts({ embed: false })
return { posts }
}
export default ({ data }) => `
<html lang="pl">
<head>
<title>Blog</title>
<link rel="stylesheet" href="/css/styles.css">
</head>
<body>
<h1>Blog (${data.posts.length})</h1>
<ul>
${data.posts
.map(
(post) => `
<li>
<a href="${postPath(post)}">${post.title.rendered}</a>
<time>${post.date.slice(0, 10)}</time>
</li>`,
)
.join('')}
</ul>
</body>
</html>
`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() {
// Pełne archiwum — przejdź stronicowaniem przez całą witrynę WP
const posts = await getAllPosts({ embed: false })
return { posts }
}
export default ({ data }) =>
html({ lang: 'pl' },
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)),
),
),
),
),
)import { getAllPosts, postPath } from '../lib/wordpress.js'
export async function data() {
// Pełne archiwum — przejdź stronicowaniem przez całą witrynę WP
const posts = await getAllPosts({ embed: false })
return { posts }
}
export default function BlogIndex({ data }) {
return (
<html lang="pl">
<head>
<title>Blog</title>
<link rel="stylesheet" href="/css/styles.css" />
</head>
<body>
<h1>Blog ({data.posts.length})</h1>
<ul>
{data.posts.map((post) => (
<li key={post.slug}>
<a href={postPath(post)}>{post.title.rendered}</a>
<time>{post.date.slice(0, 10)}</time>
</li>
))}
</ul>
</body>
</html>
)
}5. Pobierz każdy wpis do statycznych stron
generateStaticParams musi zwrócić każdy slug, który chcesz mieć w dist/. Stronicuj tu API — nie wołaj getPosts({ perPage: 100 }) raz i na tym nie poprzestawaj.
import {
getAllPosts,
getPostBySlug,
featuredImage,
} from '../lib/wordpress.js'
export async function generateStaticParams() {
const ripStarted = performance.now()
console.log(
`[wordpress] pobieram wpisy… (${process.uptime().toFixed(1)}s od startu)`,
)
// Pobierz każdy opublikowany wpis (tysiące są w porządku — 100 na żądanie)
const posts = await getAllPosts({
embed: false, // tylko slugi; pomiń _embed dla szybkości
onPage: (page, totalPages, count) => {
console.log(`[wordpress] strona ${page}/${totalPages} (${count} wpisów)`)
},
})
const ripSeconds = ((performance.now() - ripStarted) / 1000).toFixed(1)
console.log(
`[wordpress] pobrano ${posts.length} wpisów w ${ripSeconds}s` +
` (${process.uptime().toFixed(1)}s od startu)`,
)
return posts.map((post) => ({ slug: post.slug }))
}
export async function data({ params }) {
const post = await getPostBySlug(params.slug)
if (!post) throw new Error(`Nie znaleziono wpisu: ${params.slug}`)
return { post }
}
export default ({ data }) => {
const { post } = data
const image = featuredImage(post)
return `
<html lang="pl">
<head>
<title>${post.title.rendered}</title>
<link rel="stylesheet" href="/css/styles.css">
</head>
<body>
<article>
<p><a href="/blog">← Blog</a></p>
<h1>${post.title.rendered}</h1>
<time>${post.date.slice(0, 10)}</time>
${image ? `<img src="${image}" alt="">` : ''}
<div class="content">
${post.content.rendered}
</div>
</article>
</body>
</html>
`
}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] pobieram wpisy… (${process.uptime().toFixed(1)}s od startu)`,
)
// Pobierz każdy opublikowany wpis (tysiące są w porządku — 100 na żądanie)
const posts = await getAllPosts({
embed: false, // tylko slugi; pomiń _embed dla szybkości
onPage: (page, totalPages, count) => {
console.log(`[wordpress] strona ${page}/${totalPages} (${count} wpisów)`)
},
})
const ripSeconds = ((performance.now() - ripStarted) / 1000).toFixed(1)
console.log(
`[wordpress] pobrano ${posts.length} wpisów w ${ripSeconds}s` +
` (${process.uptime().toFixed(1)}s od startu)`,
)
return posts.map((post) => ({ slug: post.slug }))
}
export async function data({ params }) {
const post = await getPostBySlug(params.slug)
if (!post) throw new Error(`Nie znaleziono wpisu: ${params.slug}`)
return { post }
}
export default ({ data }) => {
const { post } = data
const image = featuredImage(post)
return html({ lang: 'pl' },
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),
),
),
)
}import {
getAllPosts,
getPostBySlug,
featuredImage,
} from '../lib/wordpress.js'
export async function generateStaticParams() {
const ripStarted = performance.now()
console.log(
`[wordpress] pobieram wpisy… (${process.uptime().toFixed(1)}s od startu)`,
)
// Pobierz każdy opublikowany wpis (tysiące są w porządku — 100 na żądanie)
const posts = await getAllPosts({
embed: false, // tylko slugi; pomiń _embed dla szybkości
onPage: (page, totalPages, count) => {
console.log(`[wordpress] strona ${page}/${totalPages} (${count} wpisów)`)
},
})
const ripSeconds = ((performance.now() - ripStarted) / 1000).toFixed(1)
console.log(
`[wordpress] pobrano ${posts.length} wpisów w ${ripSeconds}s` +
` (${process.uptime().toFixed(1)}s od startu)`,
)
return posts.map((post) => ({ slug: post.slug }))
}
export async function data({ params }) {
const post = await getPostBySlug(params.slug)
if (!post) throw new Error(`Nie znaleziono wpisu: ${params.slug}`)
return { post }
}
export default function BlogPost({ data }) {
const { post } = data
const image = featuredImage(post)
return (
<html lang="pl">
<head>
<title>{post.title.rendered}</title>
<link rel="stylesheet" href="/css/styles.css" />
</head>
<body>
<article>
<p><a href="/blog">← Blog</a></p>
<h1>{post.title.rendered}</h1>
<time>{post.date.slice(0, 10)}</time>
{image ? <img src={image} alt="" /> : null}
<div
className="content"
dangerouslySetInnerHTML={{ __html: post.content.rendered }}
/>
</article>
</body>
</html>
)
}6. Build
WP_URL=https://your-wordpress-site.com sitelo buildPierwszy build raz przechodzi przez WordPressa i wypełnia cache pobrań. Kolejne buildy korzystają z zapisanych odpowiedzi list i szczegółów (cache: 'auto' → system plików na produkcji), dopóki nie minie maxAge. Podnieś renderConcurrency w sitelo.config.js, jeśli renderujesz tysiące stron wpisów.
Uwagi
HTML z WordPressa
title.rendered i content.rendered to ciągi HTML prosto z WP. Wstaw je do szablonu bez zmian (jak wyżej) albo je odkaź, jeśli nie ufasz CMS-owi do końca.
Treści prywatne
Publiczne trasy REST wystawiają tylko opublikowane wpisy. Dla szkiców albo własnej autoryzacji przekaż nagłówki w drugim argumencie fetchWithCache (zwykły init fetch) i użyj stabilnego cacheKey.
Dokumentacja wczytywania danych · Dokumentacja routingu