#[BlockRenderer] Component to import data GraphQL-WP

4 messages · Page 1 of 1 (latest)

restive streamBOT
#

Hi @candid storm. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To create a component that renders blocks of content from WordPress using GraphQL in an Astro project, you can follow these steps:

  1. First, ensure you have set up the WordPress GraphQL plugin and have the GraphQL endpoint available.

  2. 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>
  1. 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).

  2. Use the BlockRenderer component 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.

#

@candid storm Kapa.ai is still learning and improving, please let me know how I did by reacting below.