#[Render] Content by Wordpress Headless with GraphlQL to Astro

3 messages · Page 1 of 1 (latest)

willow cipherBOT
#

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

#

Certainly! I can help you with creating a basic component in Astro to fetch content from a headless WordPress site using GraphQL. Here's a step-by-step guide to get you started:

  1. First, make sure you have an Astro project set up and a WordPress site with GraphQL enabled (you can use a plugin like WPGraphQL).

  2. Install the required dependencies. You'll need a GraphQL client like graphql-request. Run this command in your Astro project directory:

npm install graphql-request graphql
  1. Create a new component file, let's call it WordPressHome.astro, in your src/components directory.

  2. Here's a basic component that fetches the home page content from WordPress using GraphQL:

---
import { GraphQLClient } from 'graphql-request';

const endpoint = '<https://your-wordpress-site.com/graphql';>
const graphQLClient = new GraphQLClient(endpoint);

const query = `
  query HomePageQuery {
    page(id: "home", idType: URI) {
      title
      content
    }
  }
`;

const data = await graphQLClient.request(query);
const { title, content } = data.page;
---

<div>
  <h1>{title}</h1>
  <div set:html={content}></div>
</div>
  1. Now you can use this component in your Astro pages. For example, in your src/pages/index.astro:
---
import Layout from '../layouts/Layout.astro';
import WordPressHome from '../components/WordPressHome.astro';
---

<Layout title="Home">
  <WordPressHome />
</Layout>

This basic setup will fetch the title and content of your WordPress home page and render it in your Astro site. Remember to replace '<https://your-wordpress-site.com/graphql'> with your actual WordPress GraphQL endpoint.

Note that this is a very basic example. Depending on your specific needs, you might want to add error handling, loading states, or fetch more complex data structures.