WPGraphQL - GraphQL API dla WordPress
WPGraphQL dodaje GraphQL endpoint do WordPress, umożliwiając pobieranie dokładnie tych danych, których potrzebujesz. Idealne dla headless WordPress i nowoczesnych frontendów. Jedno zapytanie zamiast wielu REST calls.
Krótka odpowiedź
Instalacja i podstawy
Instalacja:
- Wtyczki → WPGraphQL
- Aktywuj
- Endpoint: domena.pl/graphql
GraphiQL IDE:
- GraphQL → GraphiQL IDE
- Testowanie zapytań w przeglądarce
- Autouzupełnianie, dokumentacja
Pierwsze zapytanie:
```graphql
query {
posts(first: 5) {
nodes {
id
title
slug
date
}
}
}
```
Odpowiedź:
```json
{
"data": {
"posts": {
"nodes": [
{"id": "...", "title": "Post", ...}
]
}
}
}
```
Zapytania - Posts, Pages, Media
Posts z detalami:
```graphql
query GetPosts {
posts(first: 10, where: {categoryName: "news"}) {
nodes {
title
slug
excerpt
date
featuredImage {
node {
sourceUrl
altText
}
}
categories {
nodes {
name
slug
}
}
}
}
}
```
Pojedynczy post:
```graphql
query GetPost($slug: ID!) {
post(id: $slug, idType: SLUG) {
title
content
date
author {
node {
name
}
}
}
}
```
Strony:
```graphql
query {
pages {
nodes {
title
slug
content
}
}
}
```
Custom Post Types i ACF
CPT w WPGraphQL:
Przy rejestracji CPT:
```php
register_post_type('portfolio', [
'show_in_graphql' => true,
'graphql_single_name' => 'project',
'graphql_plural_name' => 'projects',
// ...
]);
```
Zapytanie CPT:
```graphql
query {
projects {
nodes {
title
slug
}
}
}
```
ACF + WPGraphQL:
- Zainstaluj: WPGraphQL for ACF
- ACF pola automatycznie w schema
```graphql
query {
projects {
nodes {
title
projectFields {
client
year
technologies
}
}
}
}
```
Integracja z Next.js
Fetch w Next.js:
```javascript
async function getPosts() {
const res = await fetch('https://twoja-strona.pl/graphql', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
query: `
query {
posts(first: 10) {
nodes {
title
slug
}
}
}
`
})
});
const json = await res.json();
return json.data.posts.nodes;
}
```
Biblioteki:
- Apollo Client - pełny GraphQL client
- urql - lżejszy
- graphql-request - minimalistyczny
ISR z Next.js:
- Incremental Static Regeneration
- Statyczne strony odświeżane w tle
- Szybkość SSG + aktualność