Skip to content

docs: Next Pages template hierarchy #359

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Aug 4, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions examples/next/template-hierarchy/.wp-env.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"phpVersion": "8.3",
"plugins": [
"https://github.com/wp-graphql/wp-graphql/releases/latest/download/wp-graphql.zip"
],
"themes": ["https://downloads.wordpress.org/theme/nude.1.2.zip"],
"config": {
"WP_DEBUG": true,
"SCRIPT_DEBUG": false,
"GRAPHQL_DEBUG": true,
"WP_DEBUG_LOG": true,
"WP_DEBUG_DISPLAY": false,
"SAVEQUERIES": false
},
"mappings": {
"db": "./wp-env/db",
"wp-content/uploads": "./wp-env/uploads",
".htaccess": "./wp-env/setup/.htaccess"
},
"lifecycleScripts": {
"afterStart": "wp-env run cli -- wp theme activate nude && wp-env run cli -- wp theme delete --all && wp-env run cli -- wp rewrite structure '/%postname%/' && wp-env run cli -- wp rewrite flush"
}
}
18 changes: 18 additions & 0 deletions examples/next/template-hierarchy/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Astro Template HIerarchy and Data fetching w/URQL Example

In this example we show how to implement the WP Template Hierarchy in Astro for use with a Headless WordPress backend using WPGraphQL. We use URQL for all routing and fetching page content.

## Getting Started

> [!IMPORTANT]
> Docker Desktop needs to be installed to run WordPress locally.

1. Run `npm run example:setup` to install dependencies and configure the local WP server.
2. Run `npm run example:start` to start the WP server and Astro development server.

> [!NOTE]
> When you kill the long running process this will not shutdown the local WP instance, only Astro. You must run `npm run example:stop` to kill the local WP server.

## Trouble Shooting

To reset the WP server and re-run setup you can run `npm run example:prune` and confirm "Yes" at any prompts.
41 changes: 41 additions & 0 deletions examples/next/template-hierarchy/example-app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*

# env files (can opt-in for committing if needed)
.env*

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts
40 changes: 40 additions & 0 deletions examples/next/template-hierarchy/example-app/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/pages/api-reference/create-next-app).

## Getting Started

First, run the development server:

```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```

Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.

You can start editing the page by modifying `pages/index.js`. The page auto-updates as you edit the file.

[API routes](https://nextjs.org/docs/pages/building-your-application/routing/api-routes) can be accessed on [http://localhost:3000/api/hello](http://localhost:3000/api/hello). This endpoint can be edited in `pages/api/hello.js`.

The `pages/api` directory is mapped to `/api/*`. Files in this directory are treated as [API routes](https://nextjs.org/docs/pages/building-your-application/routing/api-routes) instead of React pages.

This project uses [`next/font`](https://nextjs.org/docs/pages/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.

## Learn More

To learn more about Next.js, take a look at the following resources:

- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn-pages-router) - an interactive Next.js tutorial.

You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!

## Deploy on Vercel

The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.

Check out our [Next.js deployment documentation](https://nextjs.org/docs/pages/building-your-application/deploying) for more details.
7 changes: 7 additions & 0 deletions examples/next/template-hierarchy/example-app/jsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"compilerOptions": {
"paths": {
"@/*": ["./src/*"]
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
};

export default nextConfig;
17 changes: 17 additions & 0 deletions examples/next/template-hierarchy/example-app/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "example-app",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"next": "^15.3.4",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"urql": "^4.2.2"
}
}
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { useRouteData } from "@/lib/context";
import TemplateHierarchyInfo from "@/components/TemplateHierarchyInfo";

export default function Layout({ children }) {
const { templateData, uri } = useRouteData();

return (
<div className="layout">
<TemplateHierarchyInfo template={templateData} uri={uri} />
<header>
<h1>Template Hierarchy Example</h1>
<nav>
<ul>
<li>
<a href="/">Home</a>
</li>
<li>
<a href="/hello-world">Sample Post</a>
</li>
<li>
<a href="/sample-page">Sample Page</a>
</li>
</ul>
</nav>
</header>
<main>{children}</main>
</div>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { gql } from "urql";
import { useRouteData } from "@/lib/context";

export default function RecentPosts() {
const { graphqlData } = useRouteData();

const posts = graphqlData?.RecentPosts?.data?.posts?.nodes || [];

if (graphqlData?.RecentPosts?.error) {
console.error("Error fetching RecentPosts:", graphqlData.RecentPosts.error);
return <div>Error loading recent posts.</div>;
}

return (
<div className="recent-posts">
<h2>Recent Posts</h2>
<ul>
{posts.map((post) => (
<li key={post.id}>
<a href={post.uri}>{post.title}</a>
</li>
))}
</ul>
</div>
);
}

RecentPosts.query = {
query: gql`
query RecentPosts {
posts(first: 5) {
nodes {
id
title
uri
}
}
}
`,
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
export default function TemplateHierarchyInfo({ template, uri }) {
return (
<aside className="template-hierarchy-info">
<section>
<strong>URI:&nbsp;</strong>
<code>{uri}</code>
</section>
<section>
<strong>Possible Templates:&nbsp;</strong>
<code>{template.possibleTemplates?.join("|")} </code>
</section>
<section>
<strong>Available Templates:&nbsp;</strong>
<code>
{template.availableTemplates
?.map((template) => template.id)
.join("|")}
</code>
</section>
<section>
<strong>Template:&nbsp;</strong>
<code> {template.template?.id} </code>
</section>
</aside>
);
}
37 changes: 37 additions & 0 deletions examples/next/template-hierarchy/example-app/src/lib/client.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Client, fetchExchange } from "urql";
export { gql } from "urql";

const GRAPHQL_URL = "index.php?graphql";
const graphqlApi = new URL(GRAPHQL_URL, "http://localhost:8888").href;

/**
* This is a very basic URQL client setup.
* It uses the fetchExchange to make network requests.
*
* You can add more exchanges like the `@urql/exchange-persisted` for network caching with WPGraphQL SmartCache.
*/
export const client = new Client({
url: graphqlApi,
exchanges: [fetchExchange],
});

export const fetchAllPaginated = async (query, getData, getPageInfo) => {
const allData = [];
let hasNextPage = true;
let after = null;

while (hasNextPage) {
const { data, error } = await client.query(query, { after });

if (error) {
console.error("Error fetching paginated data:", error);
break;
}

allData.push(...getData(data));
after = getPageInfo(data).endCursor;
hasNextPage = getPageInfo(data).hasNextPage;
}

return allData;
};
20 changes: 20 additions & 0 deletions examples/next/template-hierarchy/example-app/src/lib/context.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import React from "react";

const RouteDataContext = React.createContext();

export const useRouteData = () => {
const context = React.useContext(RouteDataContext);
if (!context) {
throw new Error(
"useRouteData must be used within a RouteDataContext.Provider"
);
}
return context;
};
export const RouteDataProvider = ({ children, value }) => {
return (
<RouteDataContext.Provider value={value}>
{children}
</RouteDataContext.Provider>
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { client, fetchAllPaginated } from "./client";

export async function fetchQueries({ queries, context, props }) {
if (!queries || queries.length === 0) {
console.error("No queries provided");
return {};
}

let queryPromises = [];

for (const query of queries) {
if (!query.query) {
console.error("Query is undefined");
continue;
}

const queryName = query.name || query.query.definitions[0].name?.value;

if (!queryName) {
console.error("Query name is undefined, skipping query");
continue;
}

const queryVariables = query.variables
? query.variables(context, props)
: {};

const queryResp = client.query(query.query, queryVariables);

queryPromises.push(
queryResp.then((response) => ({
name: queryName,
response,
}))
);
}

const allSettledQueries = await Promise.all(queryPromises);

const allResponses = {};

for (const { name, response } of allSettledQueries) {
allResponses[name] = response;
}

return allResponses;
}
Loading