Skip to content

docs: initial astro previews example #369

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 3 commits into from
Aug 18, 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
25 changes: 25 additions & 0 deletions examples/astro/previews/.wp-env.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"phpVersion": "8.3",
"plugins": [
"https://github.com/wp-graphql/wp-graphql/releases/latest/download/wp-graphql.zip",
"https://github.com/wpengine/hwptoolkit/releases/download/%40wpengine%2Fhwp-previews-wordpress-plugin-0.0.8/hwp-previews.zip",
"https://github.com/wp-graphql/wpgraphql-ide/releases/latest/download/wpgraphql-ide.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/astro/previews/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.
24 changes: 24 additions & 0 deletions examples/astro/previews/example-app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# build output
dist/

# generated types
.astro/

# dependencies
node_modules/

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

# environment variables
.env
.env.production

# macOS-specific files
.DS_Store

# jetbrains setting folder
.idea/
48 changes: 48 additions & 0 deletions examples/astro/previews/example-app/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Astro Starter Kit: Basics

```sh
npm create astro@latest -- --template basics
```

[![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/github/withastro/astro/tree/latest/examples/basics)
[![Open with CodeSandbox](https://assets.codesandbox.io/github/button-edit-lime.svg)](https://codesandbox.io/p/sandbox/github/withastro/astro/tree/latest/examples/basics)
[![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/withastro/astro?devcontainer_path=.devcontainer/basics/devcontainer.json)

> 🧑‍🚀 **Seasoned astronaut?** Delete this file. Have fun!

![just-the-basics](https://github.com/withastro/astro/assets/2244813/a0a5533c-a856-4198-8470-2d67b1d7c554)

## 🚀 Project Structure

Inside of your Astro project, you'll see the following folders and files:

```text
/
├── public/
│ └── favicon.svg
├── src/
│ ├── layouts/
│ │ └── Layout.astro
│ └── pages/
│ └── index.astro
└── package.json
```

To learn more about the folder structure of an Astro project, refer to [our guide on project structure](https://docs.astro.build/en/basics/project-structure/).

## 🧞 Commands

All commands are run from the root of the project, from a terminal:

| Command | Action |
| :------------------------ | :----------------------------------------------- |
| `npm install` | Installs dependencies |
| `npm run dev` | Starts local dev server at `localhost:4321` |
| `npm run build` | Build your production site to `./dist/` |
| `npm run preview` | Preview your build locally, before deploying |
| `npm run astro ...` | Run CLI commands like `astro add`, `astro check` |
| `npm run astro -- --help` | Get help using the Astro CLI |

## 👀 Want to learn more?

Feel free to check [our documentation](https://docs.astro.build) or jump into our [Discord server](https://astro.build/chat).
7 changes: 7 additions & 0 deletions examples/astro/previews/example-app/astro.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// @ts-check
import { defineConfig } from "astro/config";

// https://astro.build/config
export default defineConfig({
output: "server",
});
16 changes: 16 additions & 0 deletions examples/astro/previews/example-app/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "astro-previews-example-app",
"description": "A template for Astro with WordPress and URQL",
"type": "module",
"version": "0.0.1",
"scripts": {
"dev": "astro dev",
"build": "astro build",
"preview": "astro preview",
"astro": "astro"
},
"dependencies": {
"@urql/core": "^5.1.1",
"astro": "^5.6.1"
}
}
9 changes: 9 additions & 0 deletions examples/astro/previews/example-app/public/favicon.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions examples/astro/previews/example-app/src/assets/astro.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
50 changes: 50 additions & 0 deletions examples/astro/previews/example-app/src/components/Nav.astro
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
---
/**
* We've hard coded this but you can use the client to fetch this data from WP Menus!
* import { client, gql } from "../lib/client";
*/
---

<nav>
<ul>
<li>
<a href="/">Home</a>
</li>
<li>
<a href="/sample-page">Sample Page</a>
</li>
</ul>
</nav>
<style>
nav {
background: #eee;
padding: 1rem;
}
nav ul {
list-style: none;
display: flex;
gap: 1rem;
}
nav a {
text-decoration: none;
color: #333;
}
nav a:hover {
text-decoration: underline;
}
nav a:visited {
color: #666;
}
nav a:active {
color: #000;
}
nav a:focus {
outline: 2px solid #000;
}
nav a:focus-visible {
outline: 2px solid #000;
}
nav a:focus:not(:focus-visible) {
outline: none;
}
</style>
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
---
const template = Astro.locals.templateData;

if (!template) {
return null;
}
---

<aside class="template-hierarchy-info">
<section>
<strong>databaseId:</strong>
<code>{template.databaseId || "None"}</code>
</section>
<section>
<strong>URI:</strong>
<code>{Astro.originPathname}</code>
</section>
<section>
<strong>Possible Templates:</strong>
<code> {template.possibleTemplates?.join("|")} </code>
</section>
<section>
<strong>Available Templates:</strong>
<code>
{template.availableTemplates?.map((template) => template.id).join("|")}
</code>
</section>
<section>
<strong>Template: </strong>
<code> {template.template?.id} </code>
</section>

<style>
.template-hierarchy-info {
display: flex;
flex-direction: row;
flex-wrap: wrap;
background-color: #f2f483;
padding: 0.5em;
border-radius: 5px;

& section {
padding: 0.5em;
border-right: 1px solid black;

&:last-child {
border-right: none;
}
}
}
</style>
</aside>
32 changes: 32 additions & 0 deletions examples/astro/previews/example-app/src/content.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { defineCollection, z } from "astro:content";
import { readdir } from "node:fs/promises";
import { join } from "node:path";

const TEMPLATE_PATH = "wp-templates";

const templates = defineCollection({
loader: async () => {
const files = await readdir(join("src", "pages", TEMPLATE_PATH));
return files.map((file) => {
const slug = file.replace(".astro", "");

if (slug === "index") {
return {
id: slug,
path: join(TEMPLATE_PATH, "/"),
};
}

return {
id: slug,
path: join(TEMPLATE_PATH, slug),
};
});
},
schema: z.object({
id: z.string(),
path: z.string(),
}),
});

export const collections = { templates };
6 changes: 6 additions & 0 deletions examples/astro/previews/example-app/src/env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
declare namespace App {
interface Locals {
templateData?: import("./lib/templateHierarchy").TemplateData;
isPreview?: boolean;
}
}
36 changes: 36 additions & 0 deletions examples/astro/previews/example-app/src/layouts/Layout.astro
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
---
import Nav from "../components/Nav.astro";
import TemplateHierarchyInfo from "../components/TemplateHierarchyInfo.astro";
---

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="generator" content={Astro.generator} />
<title>Astro Basics</title>
</head>
<body>
<TemplateHierarchyInfo />
<Nav />
<div class="container">
<slot />
</div>
</body>
</html>

<style>
html,
body {
margin: 0;
width: 100%;
height: 100%;
font-family: sans-serif;
}
.container {
padding: 0 1rem;
background-color: #white;
}
</style>
48 changes: 48 additions & 0 deletions examples/astro/previews/example-app/src/lib/client.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { Client, fetchExchange } from "@urql/core";
export { gql } from "@urql/core";
// import { persistedExchange } from "@urql/exchange-persisted";

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;
};

export const authHeaders = (isPreview) => {
return isPreview
? {
Authorization: `Basic ${Buffer.from(
`admin:cn5AhXDQx4rgDh5dqJQatsgE`
).toString("base64")}`,
}
: undefined;
};
Loading