Fetch WordPress Posts Using GraphQL: A Quick Guide
Arun odayam
WordPress Developer | Web Designer | WordPress Website Designer | ReactJs Development | Full-Time Freelancer In Fiverr & Upwork | Writing About Web Designs & Web Development
Hello everyone! ??
I’m Arun, a WordPress developer passionate about exploring and sharing technology. Today, I’d like to introduce you to a powerful way of fetching data from WordPress using GraphQL.
If you’ve struggled with REST APIs, you’ll find that working with GraphQL can be much more intuitive and efficient. It’s straightforward to use and provides great flexibility when querying your data. Let’s dive in!
Steps to Fetch WordPress Posts via GraphQL:
1?? Install the WPGraphQL plugin: Add this plugin to your WordPress site to enable GraphQL functionality.
2?? Set up Apollo Client: This will act as your GraphQL client to interact with the WordPress API.
npm install @apollo/client graphql
3?? Design your query: Create a GraphQL query to fetch posts or any other data you need from your WordPress site.
import React from "react";
import { ApolloClient, InMemoryCache, ApolloProvider, useQuery, gql } from "@apollo/client";
const client = new ApolloClient({
uri: "https://your-wordpress-site.com/graphql", // Replace with your WordPress GraphQL endpoint
cache: new InMemoryCache(),
});
const GET_POSTS = gql`
query GetPosts {
posts {
nodes {
id
title
content
date
slug
}
}
}
`;
const Posts = () => {
const { loading, error, data } = useQuery(GET_POSTS);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<div>
<h1>WordPress Posts</h1>
{data.posts.nodes.map((post) => (
<div key={post.id}>
<h2>{post.title}</h2>
<p dangerouslySetInnerHTML={{ __html: post.content }} />
<p><strong>Date:</strong> {new Date(post.date).toLocaleDateString()}</p>
<hr />
</div>
))}
</div>
);
};
const App = () => (
<ApolloProvider client={client}>
<Posts />
</ApolloProvider>
);
export default App;
Key Notes:
Let me know if you need further clarification! ??
GraphQL opens up endless possibilities for working with WordPress data, making it easier to build dynamic, high-performing applications.
Learning something NEW follow me, for more...Code together & grow together.....
Siddha Doctor | Founder of Mayasiddha
3 个月????