Query for WordPress page / block data
Once WordPress and Tailwind CSS have been set up in your project, WordPress page / block data can be queried and rendered.
Let’s continue from the previous example querying for the homepage data:
// src/pages/index.astro
---
import { getBlockStyling } from "@wp-block-tools/styles";
import type { Block } from "@wp-block-tools/styles";
const response = await fetch(`${import.meta.env.WPGRAPHQL_URL}`, {
method: "POST",
headers: {
"content-type": "application/json"
},
body: JSON.stringify({
query: `
query PageData {
cssVariables
nodeByUri(uri: "/"){
... on ContentNode {
blocks
}
}
}
`
})
});
const {
data: {
cssVariables,
nodeByUri
}
} = await response.json();
const blocks: Block[] = nodeByUri?.blocks ?? [];
---
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<meta name="generator" content={Astro.generator} />
<title>Homepage</title>
{!!cssVariables && <style set:html={`:root{${cssVariables}}`} />}
</head>
<body>
{blocks.map((block) => {
const { styles, classes } = getBlockStyling(block);
switch(block.name){
case "core/paragraph":
return <p set:html={block.attributes?.content} class={classes} style={styles} />
default:
return null;
}
})}
</body>
</html>
Creating a working example
If you’re following this guide to build your site, the above example likely won’t render anything because a WordPress page will generally render top level blocks, such as core/template-part
and core/post-content
. Blocks like the core/paragraph
block will be rendered as child blocks within these top level blocks.
Dedicated BlockRenderer component
Usually the rendering of the blocks would be delegated to a <BlockRenderer />
component, so let’s take a look how we can create this component in the next section complete with rendering top level blocks.