#[Render] Content by Wordpress Headless with GraphlQL to Astro
3 messages · Page 1 of 1 (latest)
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:
-
First, make sure you have an Astro project set up and a WordPress site with GraphQL enabled (you can use a plugin like WPGraphQL).
-
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
-
Create a new component file, let's call it
WordPressHome.astro, in yoursrc/componentsdirectory. -
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>
- 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.
For more detailed information on using WordPress as a headless CMS with Astro, you can refer to the Astro WordPress Guide (https://docs.astro.build/en/guides/cms/wordpress/). This guide provides more in-depth information about setting up and using WordPress with Astro.