#[BlockRenderer] Component to import data GraphQL-WP
4 messages · Page 1 of 1 (latest)
To create a component that renders blocks of content from WordPress using GraphQL in an Astro project, you can follow these steps:
-
First, ensure you have set up the WordPress GraphQL plugin and have the GraphQL endpoint available.
-
Create a new Astro component, let's call it
BlockRenderer.astro, to fetch and render the blocks:
---
import { useStoryblokApi } from '@storyblok/astro'
import StoryblokComponent from '@storyblok/astro/StoryblokComponent.astro'
const { slug } = Astro.props;
// Fetch your WordPress data here using GraphQL
const response = await fetch('YOUR_WORDPRESS_GRAPHQL_ENDPOINT', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: `
query GetPageBlocks($slug: String!) {
page(id: $slug, idType: URI) {
blocks {
// Define your block structure here
}
}
}
`,
variables: {
slug: slug,
},
}),
});
const data = await response.json();
const blocks = data.data.page.blocks;
---
<div>
{blocks.map((block) => (
<StoryblokComponent blok={block} />
))}
</div>
-
Create individual components for each type of block you have in WordPress, similar to how you would with Storyblok components as described in the Storyblok guide (https://docs.astro.build/en/guides/cms/storyblok/#connecting-bloks-to-astro-components).
-
Use the
BlockRenderercomponent in your pages:
---
import BlockRenderer from '../components/BlockRenderer.astro';
---
<BlockRenderer slug="your-page-slug" />
This is a basic setup to get you started. You'll need to adjust the GraphQL query to match your WordPress schema and create the necessary components for each block type.
Remember to handle any necessary authentication for your WordPress GraphQL endpoint if it's not publicly accessible.
For more detailed information on fetching data in Astro, you can refer to the Astro data fetching guide (https://docs.astro.build/en/guides/data-fetching/#fetch-in-astro).
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@candid storm Kapa.ai is still learning and improving, please let me know how I did by reacting below.